github源码和工程文件地址:https://github.com/HuChengLing/wc

基本要求:要实现wc的基本功能即文件中字符数、单词数、行数的统计。

主要功能:文件中字符数、单词数、行数的统计和注释行统计。

设计思想:将文件中的一行字符读完来统计行数,然后运用字符数组再去分别统计字符数和单词数。

程序代码:

#include<stdlib.h>
#include<stdio.h>
#include<string>
void signalcount(char *Filename);
void main()
{

    int c = 0, w = 0, l = 0;
    int signline = 0;
    FILE *fp;
    char fileName[80];
    char ch[1024];
    //bool inword = false;//字符在单词中,inward等于ture
    printf("please input fileName:");
    gets_s(fileName);
    fp = fopen(fileName, "r");
    if (fp == NULL)
    {
        printf("can't open file %sn", fileName);
        getchar();
        exit(1);
    }
    while (!feof(fp))
    {
        fgets(ch, 1024, fp);
        l++;
        int length = strlen(ch);
        for (int i = 0; i < length; i++)
        {
            //判断是不是空格不是的话在while里面i++执行判断到下一个空格的出现或是结束  
            if (ch[i] != ' ')
            {
                w++;
                //if ((ch[i] > '0'&&ch[i]<'9' || ch[i]>'a'&&ch[i], 'z' || ch[i] > 'A'&&ch[i] < 'Z') && ch[i] != ' ')
                    //c++;
                while (ch[i] != ' '&&ch[i] != '')
                {

                    if ((ch[i] > '0'&&ch[i]<'9' || ch[i]>'a'&&ch[i], 'z' || ch[i] > 'A'&&ch[i] < 'Z') && ch[i] != ' '&&ch[i] != 'n')
                        c++;
                    i++;

                }
            }

        }
    }
        printf("一共有:%d行 %d个单词 %d个字符", l, w, c);
        signalcount(fileName);
        fclose(fp);
        system("pause");
}

void signalcount(char *filename)
{
    int len = 0, i = 0,signline = 0;
    FILE *fp;
    char str[1000];
    fp = fopen(filename, "r");
    if (fp == NULL)
    {
        printf( "请在文件中添加内容n") ;
        exit(-1);
    }
    while (!feof(fp))
    {
        fgets(str, sizeof(str), fp);
        len = strlen(str);
        for (i = 0; i<len; i++)
        {
            if ((str[i] == '/'&&str[i + 1] == '/') || (str[i] == '/'&&str[i + 1] == '*'))
            {
                signline++;
                break;
            }
        }
    }
    fclose(fp);
    printf( "注释行数%d行n", signline);
}

自己虽然是自己写了一些但是自己也借鉴了许多网上的代码。而且现在还存在着不能读汉字的bug有待改进。

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程