我必须用 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;
}
最佳答案
为什么如果我删除粗体行,程序就不再工作了? 该行是
getc(stdin);
当您输入字符(读入b
)时,您将在输入流中留下换行符。 fgets() 函数读取该换行符并停止读取进一步的输入。这就是为什么额外调用 getc()
使其工作,因为它消耗换行符 - 因此 fgets()
等待您想要的输入。
stdio 的标准输入函数(scanf
、fgets
、getc
等)很奇怪,经常会导致微妙的错误。通常首选逐行读取输入,然后进行解析以尽量减少意外错误。
关于计算字符串中的字符 (C) - 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774570/