[英]Why doesn't the printf statement execute here after entering some text and pressing the “enter” key (EOF)?
該代碼源自“ The C Programming Language,第二版”:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF)
++nc;
printf("%s: %ld\n", "number of characters", nc);
}
為什么按下“ enter”鍵(EOF)后,“ printf”語句不執行?
Enter鍵不是 EOF。 根據您的系統,它將發送回車符(0x0D或'\\r'
),換行符(0x0A或'\\n'
)或兩者。
在Linux(可能是Unix)上,可以通過Ctrl + D發送EOF。 在Windows上,應為Ctrl + Z(但稍后可能需要按Enter鍵)。
如果要在按ENTER鍵之后執行該printf
,則應將其更改為:
while(getchar() != EOF)
至:
while(getchar() != '\n')
EOF(文件結尾)與ENTER不同。
您可能要考慮購買一本更新的書。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.