• WordCount


        程序要求需要统计文本文件中的字符数,单词数,行数信息。

        定义一个统计信息的函数int *getCharNum(char *fileName,int *totalNum),形参为文件名称以及统计得到的字符数,单词数,行数,返回值为totalNum;

    使用了fgets(buf,size,fp)函数,遇到EOF则返回;按行读取;每一行结束处理换行字符“ ”也算该行字符;对于大小为size的buf,最多只读取size-1个字节;自动地把buf中最后一个字符后添加一个“/0”;函数代码如下:

    int *getCharNum(char *fileName, int *totalNum)
    {
        int charcount = 0;
        int rowcount = 0;
        int wordcount = 0;
        int lastIsBlank = 0;
        int slen;
        char c;
        char s[10];
        FILE *fp;
        fp = fopen("fileName", "r");
        if (fp  == NULL)
        {
            printf("the file can not open
    ");
            return NULL;
        }
        else
        while (fgets(s, 10, fp)!= NULL)
        {
            slen = strlen(s);
            for (int i = 0; i < slen; i++)
            {
                c = s[i];
                if (c == ' ' || c == '	')
                {
                    if (!lastIsBlank)
                    {
                        wordcount++;
                        lastIsBlank = 1;
                    }
                }
                if (c == '
    ' || c == '
    ')
                {
                    rowcount++;
                    lastIsBlank = 0;
                }
                if (c == ',' || c == '!' || c == '.' || c == '#' || c == '|' || c == '%' || c == '=' || c == '&' || c == '*' || c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == '<' || c == '>' || c == ';' || c == '/')
                {
                    charcount++;
                    lastIsBlank = 1;
                }
            }
        }
        totalNum[0] = wordcount;
        totalNum[1] = rowcount;
        totalNum[2] = charcount;
        return totalNum;
    
    }

    主函数部分,通过输入需要分析的文件的名字,调用函数,完成分析。

    void main()
    {
        char fileName[30];
        int totalNum[3];
        printf("Input file name
    ");
                      scanf("%s",fileName);
        if (getCharNum(fileName, totalNum))
        {
            printf("单词数为%d
    ", totalNum[0]);
            printf("回车数为%d
    ", totalNum[1]);
            printf("字符数为%d
    ", totalNum[2]);
        }
        else
            printf("error
    ");
        system("pause");
    }

    运行测试

    以为在coding上传就可以,所以没有写博客。后来是同学说才知道,从这件事我总结!一定要跟同学多沟通!!

  • 相关阅读:
    开源软件的国内镜像
    ruby学习之路(一)
    VBS正则表达式
    fscanf和feof的组合使用
    计算机产生随机数
    常用:JQ
    unitegallery 测试使用-自动播放关闭
    H5重力感应(转)
    JS中,如何判断一个数是不是小数?如果是小数,如何判断它是几位小数 保留n位小数
    input禁止显示历史输入记录
  • 原文地址:https://www.cnblogs.com/cuilulu/p/5313114.html
Copyright © 2020-2023  润新知