问题陈述:一个 C 程序来计算一个字符在文件中出现的次数。字符被认为不区分大小写。 我已将输入字符和文件中的字符都转换为大写,以便字符的出现不会被忽略。但是当我在在线编辑器上执行此操作时,得到的结果是“错误答案”,编辑器不接受此代码。这段代码有什么错误??
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
int main
{
FILE *fp;
char filename[20];
char character;
char compare;
int to_upper1;
int to_upper2;
int count=0;
printf("\nEnter the file name");
scanf("%s", filename);
fp = fopen(filename,"r");
if(fp == NULL)
{
exit(-1);
}
printf("\nEnter the character to be counted");
scanf("%c", &character);
to_upper1 = toupper(character);
while((compare = fgets(fp)) != EOF)
{
to_upper2 = toupper(compare);
if(to_upper1 == to_upper2)
count++;
}
printf("\nFile \'%s\' has %d instances of letter \'%c\'", filename, count, character);
return 0;
}
最佳答案
我在您的代码中发现了一些错误,并做了一些小调整。错误是 - 没有吃掉字符输入之前的“空白”,使用 fgets()
而不是 fgetc()
,在 '
之前使用转义字符输出文本中的 code> 符号。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void) // added arg for compilability
{
FILE *fp;
char filename[20];
char character;
int compare; // correct type for fgetc and toupper
int to_upper1;
int to_upper2;
int count=0;
printf("Enter the file name: ");
scanf("%19s", filename); // restrict length
fp = fopen(filename,"r");
if(fp == NULL)
{
printf ("Cannot open file '%s'\n", filename);
exit(-1);
}
printf("\nEnter the character to be counted: ");
scanf(" %c", &character); // filter out whitespace
to_upper1 = toupper((int)character);
while((compare = fgetc(fp)) != EOF) // changed from fgets()
{
to_upper2 = toupper(compare);
if(to_upper1 == to_upper2)
count++;
}
fclose(fp); // remember to close file!
printf("File '%s' has %d instances of letter '%c'", filename, count, character);
return 0;
}
关于C语言不区分大小写地统计某个字符在文件中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868426/