字数统计程序不产生所需的输出

问题描述 投票:-4回答:1

我指的是K&R学习C.我没有得到以下代码的所需输出。

#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
    int c,nl,nw,nc, state;
    nl = nc = nw = 0;
    state = OUT;
    while ((c=getchar()!= EOF))
    {
        ++nc;
        if (c == '\n')
        {
            ++nl;
        }
        if (c ==' ' || c == '\n' || c == '\t')
            state = OUT;
        else if (state == OUT)
        {
            state = IN;
            ++nw;
        }
    }
    printf("%d %d %d", nc, nw,nl);
}

我给出了以下输入

the
door is
open

我获得的输出是

17 1 0

请告诉我代码中有什么问题。

c word-count
1个回答
1
投票

c=getchar()!= EOF错了。这将首先调用函数getchar()。然后它会将返回值与EOF进行比较。之后,比较结果将为1或0,将分配给c

要避免这种情况,请改用(c=getchar()) != EOF

而不是第二个if语句,使用if(isspace(c))(感谢Lundin指出)

您还应指定main应返回int以避免警告。

© www.soinside.com 2019 - 2024. All rights reserved.