2011-09-18 102 views
1

我目前正在嘗試通過使用K & R來學習C,但我完全被示例1.5.2難倒了。出於某種原因,在按下Ctrl-Z之後,而不是打印nc,它會打印nc乘以2.我不知道可能是什麼原因導致了這個問題(我完全複製了代碼中的代碼)。我使用的編譯器是Visual Studio 2010中這裏是代碼:難倒K&R練習1.5.2

#include <stdio.h> 

main() 
{ 

long nc; 

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


} 
+0

我假設你的意思是「它打印2 「,而不是」nc乘以2「。我猜Ctrl + Z正在生成2個按鍵。 –

+1

因爲'enter'是一個按鍵。 –

+0

哦,我現在看到了,這就是爲什麼每個按鍵都註冊兩次而不是一次。 – Emryss

回答

2

因爲enter是擊鍵。

如果輸入的是:

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

將輸出:

1

不知道爲什麼你得到你所描述的行爲,但應該是%ld的不1D%

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 
+0

他在輸入的每個字母后都打'enter'(導致'nc'是他預期的兩倍)。看評論。 –

+0

啊哈,那麼趕上。 :) –