C 被K&;R练习1.5.2

C 被K&;R练习1.5.2,c,kernighan-and-ritchie,C,Kernighan And Ritchie,我目前正试图使用K&R学习C,但我完全被示例1.5.2难住了。出于某种原因,在我按下Ctrl-Z键后,它不会打印nc,而是打印乘以2的nc。我不知道是什么导致了这个问题(我复制了书中的代码)。我使用的编译器是VisualStudio2010。代码如下: #include <stdio.h> main() { long nc; nc = 0; while (getchar() != EOF) ++nc; printf("%1d\n", nc); } #包括 main

我目前正试图使用K&R学习C,但我完全被示例1.5.2难住了。出于某种原因,在我按下Ctrl-Z键后,它不会打印
nc
,而是打印乘以2的
nc
。我不知道是什么导致了这个问题(我复制了书中的代码)。我使用的编译器是VisualStudio2010。代码如下:

#include <stdio.h>

main()
{

long nc;

nc = 0;
while (getchar() != EOF)
    ++nc;
printf("%1d\n", nc);


}
#包括
main()
{
长nc;
nc=0;
while(getchar()!=EOF)
++数控;
printf(“%1d\n”,nc);
}

不确定为什么会出现您描述的行为,但这应该是%ld而不是%1d

因为
输入
是一次按键

如果您的输入是:

1<enter>
1<enter>
1<enter>
^z
1
1.
1.
^z
它将输出:

六,


无法重现您的错误。我添加了一些调试语句

#include <stdio.h>

main() {
     int nc = 0, ch;

     while ((ch = getchar()) != EOF) {
          printf("%d\n", ch);
          ++nc;
     }
     printf("nc - %1d\n", nc);


}
然后使用Visual Studio 2008:

E:\temp>cl eof.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

eof.c
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:eof.exe
eof.obj

E:\temp>eof
^Z
nc - 0

E:\temp>eof
foo bar
102
111
111
32
98
97
114
10
^Z
nc - 8

我想你的意思是“它打印2”,而不是“nc乘以2”。我猜Ctrl+Z会产生两次击键。因为
enter
是一次击键。哦,我现在明白了,这就是为什么每次击键都记录两次而不是一次的原因。移动到一个答案,因为,嗯,它是:)在他键入的每个字母之后,可能都重复了他所击的
enter
(导致
nc
比他预期的大一倍)。参见注释。
E:\temp>cl eof.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

eof.c
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:eof.exe
eof.obj

E:\temp>eof
^Z
nc - 0

E:\temp>eof
foo bar
102
111
111
32
98
97
114
10
^Z
nc - 8