计算字符串中的字符(C)-问题

我必须用C编写一个程序,该程序可以找到我选择的字符的幻影次数。 这是我的代码: 为什么如果我删除粗体行,程序将不再起作用?我的意思是我不明白那条线在做什么。

#include <stdio.h>
#include <string.h>

int number(char c)
{
    int i,nr=0;
    char s[50];
    printf("Enter a string: ");
    fgets(s,49,stdin);
    for(i=0;i<strlen(s);++i)
        {
            if(s[i]==c)
            {
                nr++;
            }
        }
    return nr;
}

int main()
{
    int nra;
    char b;
    printf("Enter a character you want to count: ");
    b=getc(stdin);
    **getc(stdin);**
    printf("Call the function\n");
    nra=number(b);
    printf("The number of apparitions of chracter %c is  %d",b,nra);
    return 0;
}

Davids168 回答:计算字符串中的字符(C)-问题

为什么如果我删除粗体行,程序将不再起作用? 随着线被

getc(stdin);

输入字符(读入b)时,将在输入流中保留换行符。 fgets()函数读取该换行符,并停止读取其他输入。这就是为什么对getc()的额外调用使它工作时会消耗换行符-因此fgets()等待您的预期输入。

来自stdio的标准输入函数(scanffgetsgetc等)是古怪的,经常会导致细微的错误。通常最好先逐行读取输入,然后进行解析,以最大程度地减少意外错误。

本文链接:https://www.f2er.com/3134777.html

大家都在问