【问题标题】:Error in counting the number of times a character appears in a file in Case insensitive manner以不区分大小写的方式计算字符在文件中出现的次数时出错
【发布时间】:2015-07-13 21:00:58
【问题描述】:

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

"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;
}` 

【问题讨论】:

  • 您的意见是什么?文件的内容是什么?尝试在scanf("%c",&amp;ch); 中的%c 之前添加一个空格

标签: c file-io char scanf fgetc


【解决方案1】:

第 1 点

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

 fp=fopen(f,"r");

第 2 点

改变

scanf("%c",&ch);

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

避免之前按 ENTER 键存储的尾随换行符 (\n)。

第 3 点

根据fgetc()man page,返回类型为int。将cmp的数据类型从char改为int

注意:

  1. main()的推荐签名是int main(void)
  2. 初始化局部变量总是一种很好的做法。

【讨论】:

    猜你喜欢
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多