在線編輯器中執行此代碼,但總是得到File 'test.txt' has 0 instances of letter 'r'
。該怎麼辦? File 'test.txt' has 99 instances of letter'r'
。這是預期的輸出。程序計算一個字符出現在文件中的次數(不區分大小寫)
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fptr;
int d=0;
char c;
char ch,ck;
char b[100];
printf("Enter the file name\n");
scanf("%19s",b);
fptr=fopen(b,"r");
printf("Enter the character to be counted\n");
scanf(" %c",&c);
c=toupper(c);
if(fptr==NULL)
{
exit(-1);
}
while((ck=fgetc(fptr))!=EOF)
{
ch=toupper(ck);
if(c==ch||c==ck)
++d;
}
fclose(fptr);
printf("File '%s' has %d instances of letter '%c'.",b,d,c);
return(0);
}
'龜etc()''返回int',所以'ck'也應該是一個'int'。 – alk
爲什麼'19'在這裏'scanf(「%19s」,b);'當'b'最多可以保存99個字符時,NUL終止符爲+1?順便說一句,發佈'test.txt'的內容。 –
除了'ck'的問題,代碼看起來不錯。 – alk