我编写了一个C程序来计算输入字符的出现次数.当我执行时,我只能输入文件名.在输入要计数的字符之前,下一个语句会执行.我得到的输出如下所示.
Enter the file name test.txt Enter the character to be counted File test.txt has 0 instances of
这是我的代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1;
int cnt=0;
char a,ch,name[20];
printf("Enter the file name\n");
scanf("%s",name);
//fp1=fopen(name,"r");
printf("Enter the character to be counted\n");
scanf("%c",&ch);
fp1=fopen(name,"r");
while(1)
{
a=fgetc(fp1);
if (a==ch)
cnt=cnt+1;
if(a==EOF)
break;
}
fclose(fp1);
printf("File %s has %d instances of %c",name,cnt,ch);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
怎么解决这个?
这是一个常见的初学者问题,尤其是在使用scanf函数族时.
问题是,当你输入文件名,然后按Enter,该scanf函数会读取文本,但Enter在输入缓冲区中保留键,换行符,所以当你下次读取一个字符时,它将读取该换行符.
解决方案非常简单:scanf通过在scanf格式中放置一个空格来告诉读取并丢弃任何前导空白区域:
scanf(" %c",&ch);
// ^
// |
// Note leading space
Run Code Online (Sandbox Code Playgroud)
如果你按照scanf参考链接,它会告诉你几乎所有的格式都会自动读取并丢弃领先的空格,三个例外中的一个只是读取单个字符的格式,"%c".