我指的是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=getchar()!= EOF
错了。这将首先调用函数getchar()
。然后它会将返回值与EOF
进行比较。之后,比较结果将为1或0,将分配给c
。
要避免这种情况,请改用(c=getchar()) != EOF
。
而不是第二个if语句,使用if(isspace(c))
(感谢Lundin指出)
您还应指定main应返回int以避免警告。