c中的字数统计程序计数超过应有的数量

时间:2013-06-22 05:31:20

标签: c switch-statement

好的伙计们,所以我写了这个程序

#include <stdio.h>

/* count words */

main ()
{

    int c, c2;
    long count = 0;

    while ((c = getchar()) != EOF)
    {
        switch(c)
        {
        case ' ':
        case '\n':
        case '\t':
            switch(c2)
            {
            case ' ':
            case '\n':
            case '\t':
                break;
            default:
                ++count;
            }
        }
        c2 = c;
    }
    printf("Word count: %ld\n", count);
}

正如您所看到的,它会根据输入对单词进行计数。所以我写了一个名为a-text的文件只有

a text

我在ubuntu提示符中写道

./cw < a-text

并写了

Word count: 2

那么,到底是什么?不应该只计算1,因为在第二个单词之后没有标签也没有新行也没有空格,只有EOF。为什么会这样?

2 个答案:

答案 0 :(得分:0)

为什么不计算单词而不是空格?然后,当输入以空格结束时,您没有问题。

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

int main(int argc, char**argv) {
    int was_space = 1;
    int c;
    int count = 0;
    while ((c = getchar()) != EOF) {
        count += !isspace(c) && was_space;
        was_space = isspace(c);
    }
    printf("Word count: %d\n", count);
    return 0;
}

答案 1 :(得分:0)

让我们看看“文字”会发生什么

after the first iteration, c2 == 'a', count remains 0
now comes c == ' ' c2 is still 'a', so count == 1, c2 becomes == ' '
now comes c == 't' c2 is still ' '. so count remains == 1
...
now comes c == '\n' c2 is the last 't'. count becomes == 2

IOW

"a text\n"
  ^----^-------- count == 1
       |
       +-------- count == 2