找到你要的答案

Q:Error in counting the number of times a character appears in a file in Case insensitive manner

Q:以不区分大小写的方式在文件中显示字符出现次数的错误

Please tell me what is wrong with below code. After executing it is showing

"test.txt has 0 instances of letter 'r'"

`#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
  FILE *fp;
  char ch,cmp;
  char f[100];
  int count=0,tu1,tu2;
  printf("Enter the file name\n");
  scanf("%s",f);
  fp=fopen(f,"r");
  printf("Enter the character to be counted\n");
  scanf("%c",&ch);
  tu1=toupper((int)ch);
  while((cmp=fgetc(fp))!=EOF)
  {
    tu2=toupper((int)cmp);
    if(tu1==tu2)
    {
      count++;
    }
  }
  fclose(fp);
  printf("\nFile \'%s\' has %d instances of letter \'%c\'",f,count,ch);
  return 0;
}` 

请告诉我下面代码有什么问题。执行后,它显示

“test.txt有字母“R”的0个实例

`#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
  FILE *fp;
  char ch,cmp;
  char f[100];
  int count=0,tu1,tu2;
  printf("Enter the file name\n");
  scanf("%s",f);
  fp=fopen(f,"r");
  printf("Enter the character 到 be counted\n");
  scanf("%c",&ch);
  tu1=到upper((int)ch);
  while((cmp=fgetc(fp))!=EOF)
  {
    tu2=到upper((int)cmp);
    if(tu1==tu2)
    {
      count++;
    }
  }
  fclose(fp);
  printf("\nFile \'%s\' has %d instances of letter \'%c\'",f,count,ch);
  return 0;
}` 
answer1: 回答1:

Point 1

Always check for the sucess of fopen() before using teh returned file pointer. Add a NULL check for fp after this (below) line of code. If NULL, discontinue the program

 fp=fopen(f,"r");

Point 2

Change

scanf("%c",&ch);

to

scanf(" %c",&ch); // mind the ' ' before c

to avoid the trailing newline (\n) stored by previous ENTER key press.

Point 3

As per the man page of fgetc(), the return type is int. Change the data type of cmp from char to int.

Note:

  1. The recommended signature of main() is int main(void)
  2. It is always a good practive to initlize the local variables.

点1

经常检查使用前的fopen()成功的返回文件指针。这之后添加FP空检查(下)行代码。如果NULL,停止程序

 fp=fopen(f,"r");

点2

改变

scanf("%c",&ch);

scanf(" %c",&ch); // mind the ' ' before c

到 avoid the trailing newline (\n) s到red by previous ENTER key press.

点3

As per the man page of fgetc(), the return type is int. 改变 the data type of cmp from char 到 int.

注:

  1. The recommended signature of main() is int main(void)
  2. It is always a good practive 到 initlize the local variables.
c  file-io  char  scanf  fgetc