C 字计数程序不能产生所需的输出
我指的是K&R学习C。我没有得到下面代码所需的输出C 字计数程序不能产生所需的输出,c,word-count,C,Word Count,我指的是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') {
#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);
}
我得到的结果是
17 1 0
请告诉我代码中有什么错误。c=getchar()!=EOF
错误。这将首先调用函数getchar()
。然后将返回值与EOF
进行比较。然后,比较结果(1或0)将分配给c
要避免这种情况,请使用(c=getchar())!=EOF
instad
使用if(isspace(c))
代替第二条if语句(感谢Lundin指出)
还应指定main应返回int以避免警告。是否尝试调试?'(c=getchar()!=EOF)-->'(c=getchar())!=EOF'Enable compiler warnings,
-Wall-Wextra
在gcc上,-Weverything
用于clang或/Wall
用于VS(cl.exe
),并且在代码编译之前不发出警告,不要接受代码。但是您没有说明程序应该做什么。或者使用ctype.h中的isspace()
。@Lundin True。谢谢已修复。这将连续空格计为单词。OP的state变量覆盖了该情况,将c
声明为char
将不起作用getchar()
返回一个int
,以区分EOF
和char 255(或-1,如果签名)@king_-nak我想我需要一些睡眠。大脑完全冻结。谢谢
17 1 0