C中支持单字母输入的字数统计

时间:2019-02-27 01:36:21

标签: c getchar

我遇到一些问题,因为'wordcount'缺少正确的数字,例如'I',因此无法正确计数。

基本上,如果一个字符/符号或独立字符/符号之间的空格将对字数进行计数。

#include <stdio.h>

int main()
{
    int wordcount;
    int ch;
    char lastch = -1;

    wordcount = 0;

    while ((ch = getc(stdin)) != EOF) {
        if (ch == ' ' || ch == '\n')
        {
            if (!(lastch == ' ' && ch == ' '))
            {
                wordcount++;
            }
        }
        lastch = ch;
    }

    printf("The document contains %d words.", wordcount);
}

1 个答案:

答案 0 :(得分:2)

您使条件测试过于复杂。如果我了解您的目的,那么您唯一关心的就是lastch != ' '(ch == ' ' || ch == '\n')之一。

此外,getchar返回类型int。因此,ch的类型应为int,以在所有系统上正确检测到EOF

简化这些更改,您可以执行以下操作:

#include <stdio.h>

int main (void) {

    int wordcount = 0,
        lastch = 0,     /* just initialize to zero */
        ch;             /* ch should be an int */

    while ((ch = getc (stdin)) != EOF) {
        if (lastch && lastch != ' ' && (ch == ' ' || ch == '\n'))
            wordcount++;
        lastch = ch;
    }
    if (lastch != '\n') /* handle no '\n' on final line */
        wordcount++;

    printf ("The document contains %d %s.\n", 
            wordcount, wordcount != 1 ? "words" : "word");

    return 0;
}

使用/输出示例

$ echo "     " | ./bin/wordcnt
The document contains 0 words.

$ echo "   t  " | ./bin/wordcnt
The document contains 1 word.

$ echo "   t t  " | ./bin/wordcnt
The document contains 2 words.

注意:为了防止文件的极端情况不包含POSIX eof(例如文件末尾的'\n'),您可以需要添加一个至少已找到一个字符的附加标志,并在退出循环后组合检查lastch,例如

#include <stdio.h>

int main (void) {

    int wordcount = 0,
        lastch = 0,     /* just initialize to zero */
        ch,             /* ch should be an int */
        c_exist = 0;    /* flag at least 1 char found */

    while ((ch = getc (stdin)) != EOF) {
        if (lastch && lastch != ' ' && (ch == ' ' || ch == '\n'))
            wordcount++;
        if (ch != ' ' && ch != '\n')    /* make sure 1 char found */
            c_exist = 1;
        lastch = ch;
    }
    if (c_exist && lastch != '\n')  /* handle no '\n' on final line */
        wordcount++;

    printf ("The document contains %d %s.\n", 
            wordcount, wordcount != 1 ? "words" : "word");

    return 0;
}

案例案例

$ echo -n "   t" | ./bin/wordcnt
The document contains 1 word.