统计文本文件中各类字符个数,代码运行错误


#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
    int c1=0,c2=0,c3=0;
    char ch;
    FILE *fp;
    fp=fopen("创建文本文件f1.txt","r");
    while(!feof(fp))
    {
        ch=fgetc(fp);
        if(ch>'0'&&ch<'9')
            c1++;
        else if(ch>'a'&&ch<'z')
            c2++;
        else if(ch>'A'&&ch<'Z')
            c2++;
        else
            c3++;
    }
    printf("letter=%d,digit=%d,other=%d",c1,c2,c3);
    return 0;
}
    

存在一些代码问题:

  • c1、c2、c3这三个变量分别记录了数字、小写字母和大写字母的个数,但是你的代码中将大写字母和小写字母的个数都统计在了c2中。应该将大写字母的统计放在单独的一个分支中。
  • 代码中没有将文件关闭。记得在程序结束时调用fclose函数关闭文件。

修改后的代码如下:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
    int c1=0,c2=0,c3=0;
    char ch;
    FILE *fp;
    fp=fopen("创建文本文件f1.txt","r");
    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }
    while(!feof(fp))
    {
        ch=fgetc(fp);
        if(ch>'0'&&ch<'9')
            c1++;
        else if(ch>='a'&&ch<='z')
            c2++;
        else if(ch>='A'&&ch<='Z')
            c2++;
        else
            c3++;
    }
    printf("letter=%d,digit=%d,other=%d",c2,c1,c3);
    fclose(fp);
    return 0;
}

可能是因为以下几种原因:

1、文件路径不正确:确保文件在你预期的位置,并且文件名没有打错。

2、文件打开失败:可能是因为文件不存在或者无法访问。

3、代码中的字符范围判断有误:在判断字符是否为数字时,应该使用 ch >= '0' && ch <= '9' 而不是 ch > '0' && ch < '9',因为字符 '9' 也是数字。同理,在判断字符是否为小写字母时,应该使用 ch >= 'a' && ch <= 'z',在判断字符是否为大写字母时,应该使用 ch >= 'A' && ch <= 'Z'。

4、使用了未初始化的变量:在使用变量之前,一定要确保它们已经被初始化。
望采纳。


#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main()
{
    // 初始化计数器
    int count_digits = 0;
    int count_letters = 0;
    int count_others = 0;

    char ch;
    FILE *fp;
    // 打开文件
    fp = fopen("创建文本文件f1.txt", "r");
    // 如果文件打开失败,则打印错误信息并退出程序
    if (fp == NULL) {
        printf("Error: failed to open file\n");
        return 1;
    }

    // 循环读取文件中的每一个字符
    while (1) {
        ch = fgetc(fp);
        // 如果读取到了文件末尾,则退出循环
        if (ch == EOF) {
            break;
        }
        // 统计字符数
        if (ch >= '0' && ch <= '9') {
            count_digits++;
        } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
            count_letters++;
        } else {
            count_others++;
        }
    }
    // 关闭文件
    fclose(fp);

    // 输出统计的结果
    printf("digits = %d, letters = %d, others = %d\n", count_digits, count_letters, count_others);

    return 0;
}