首页 > 试题广场 >

统计文本文件中各类字符个数: 分别统计一个文本文件中字母、数

[问答题]

统计文本文件中各类字符个数: 分别统计一个文本文件中字母、数字及其他学符的个数。试编写相应程序。

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    FILE *fp = fopen("test1.txt","r");
    char ch;
    int word_cnt = 0, num_cnt = 0,others_cnt = 0;

    if(!fp){
        printf("file read error\n");
        exit(0);
    }

    while((ch = fgetc(fp))!=EOF){   //用EOF作为控制条件比feof()要好,feof()会多统计一个EOF文件结束符
    //while(!feof(fp)){
        //ch = fgetc(fp);

        if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
            word_cnt++;
        else if(ch>='0'&&ch<='9')
            num_cnt++;
        else if(ch == '\n')     //多行文本的字符统计一定要把换行符排除掉
            continue;
        else
            others_cnt++;
    }

    printf("words:%d ,number:%d ,others:%d\n",word_cnt,num_cnt,others_cnt);

    if(fclose(fp)){
        printf("file close error\n");
        exit(0);
    }

    return 0;
}

发表于 2022-03-05 12:58:53 回复(0)
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char c;
    FILE *fp;
    char n1,n2,n3;
    n1=n2=n3;
    int n;
    if((fp=fopen("C:\\666.txt","r"))==NULL)
    {
        printf("文件打开失败\n");
        exit(0);
    }
    while((c=fgetc(fp))!=EOF)
    {
        if(('A'<=c)&&(c<='z'))
        {
            n1++;
        }else if(('0'<=c)&&(c<='9'))
        {
            n2++;
        }else
        {
            n3++;
        }
    }
    printf("字母数量%d\n",n1);
    printf("数字数量%d\n",n2);
    printf("其他字符数量%d\n",n3);
}

发表于 2018-06-18 09:29:30 回复(0)