1

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

#include <stdio.h>

main()
{

long nc;

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


}
4

3 回答 3

2

因为enter是按键。

如果您的输入是:

1<enter>
1<enter>
1<enter>
^z

它会输出:

6

于 2011-09-18T06:35:51.753 回答
1

不知道为什么你会得到你描述的行为,但这应该是 %ld 而不是 %1d

于 2011-09-18T06:32:59.410 回答
0

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

#include <stdio.h>

main() {
     int nc = 0, ch;

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


}

然后gcc在 Windows 上进行了尝试:

E:\temp>gcc eof.c

E:\temp>a
^Z
nc - 0

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

然后使用 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
于 2011-09-18T06:40:43.347 回答