被K& R练习所困扰1.5.2

时间:2011-09-18 06:27:28

标签: c kernighan-and-ritchie

我目前正在尝试使用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);


}

3 个答案:

答案 0 :(得分:2)

因为enter是一次击键。

如果您的输入是:

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

它会输出:

  

6

答案 1 :(得分:1)

不确定为什么会得到您描述的行为但应该是%ld而不是%1d

答案 2 :(得分:0)

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

#include <stdio.h>

main() {
     int nc = 0, ch;

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


}

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

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