0

我正在尝试从 .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);
}
4

1 回答 1

0

您必须将计数初始化为0. 否则,您的程序将不正确(将调用未定义的行为)。

int lines = 0, characters = 0, uppercase = 0,lowercase = 0;
于 2018-08-13T10:35:51.660 回答