计算字符以不区分大小写的方式出现在文件中的次数出错

时间:2021-10-09 21:48:10

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

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

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

“test.txt有0个字母'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;
}` 

1 个解决方案

#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

在使用返回的文件指针之前,请务必检查fopen()的成功。在此(下面)代码行之后为fp添加NULL检查。如果为NULL,则停止该程序

 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.

避免按上一个ENTER键存储的尾随换行符(\ n)按下。

Point 3

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

根据fgetc()的手册页,返回类型为int。将cmp的数据类型从char更改为int。

Note:

  1. The recommended signature of main() is int main(void)
  2. main()的推荐签名是int main(void)

  3. It is always a good practive to initlize the local variables.
  4. 初始化局部变量始终是一个很好的实践。

#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

在使用返回的文件指针之前,请务必检查fopen()的成功。在此(下面)代码行之后为fp添加NULL检查。如果为NULL,则停止该程序

 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.

避免按上一个ENTER键存储的尾随换行符(\ n)按下。

Point 3

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

根据fgetc()的手册页,返回类型为int。将cmp的数据类型从char更改为int。

Note:

  1. The recommended signature of main() is int main(void)
  2. main()的推荐签名是int main(void)

  3. It is always a good practive to initlize the local variables.
  4. 初始化局部变量始终是一个很好的实践。