字数统计程序可打印不同的字数

时间:2018-08-13 10:31:51

标签: c

我试图计算.txt文件中的单词,线条,字符,元音,大小写等。结果却有所不同。.当我仅计算线条和字符时,它会打印出正确的结果。但是当我加上大写和小写的计数时,它会打印出大量的行和字符计数(例如32974)。我猜我的逻辑有错误吗?谢谢。

#include <stdio.h>
#include <ctype.h>

int main(int argc, const char *argv[])
{
    int nextChar = getchar();

    int lines, characters, uppercase,lowercase;

    while (nextChar != EOF)
    {
        if (isalpha(nextChar) || isblank(nextChar) || ispunct(nextChar))
        {
            characters++;
        } else if (isspace(nextChar)){
            characters++;
            lines++;
        }

        if(isalpha(nextChar) && isupper(nextChar)){
            uppercase++;
        } else if (isalpha(nextChar) && islower(nextChar)){
            lowercase++;
        }
        nextChar = getchar();
    }
    printf("%d lines\n",lines);
    printf("%d characters\n",characters);
    printf("%d lowercase\n",lowercase);
    printf("%d uppercase\n",uppercase);
}

1 个答案:

答案 0 :(得分:0)

您必须将计数初始化为0。否则,您的程序将格式错误(将调用未定义的行为)。

int lines = 0, characters = 0, uppercase = 0,lowercase = 0;