C语言不区分大小写地统计某个字符在文件中出现的次数

标签 c file-handling case-insensitive

问题陈述:一个 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/

相关文章:

python - 为非 C 程序员解释的缓冲区和内存 View 对象

c - 程序以逆 s 顺序遍历 m*m 矩阵

c - pthread_create segfault(缓冲读取器示例)

c - 如何制作 fscanf,扫描单个单词而不是整行

php - 如何使用正则表达式匹配不区分大小写的unicode字符?

MySQL 不区分大小写的连接

c - 函数声明和括号之间的参数声明是什么意思?

c - 无法打开 d : drive 中的文件

java - 如何用Java读取/写入文件

ruby - 如何编写一个 CSS 选择器,以不区分大小写的方式查找以文本开头的元素?