【问题标题】:Word count program printing different counts字数统计程序打印不同的字数
【发布时间】:2019-01-20 01:31:12
【问题描述】:

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

【问题讨论】:

  • int lines, characters, uppercase,lowercase; 介意初始化你的变量吗?
  • 谢谢你,这么简单我不知道我是怎么错过的。我太专注于逻辑了。

标签: c


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    相关资源
    最近更新 更多