[英]c++ primer 5th 1.4.4 why can't std::cout type out things immediately
“c ++ primer 5th”1.4.4代碼示例是這樣的
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal) {
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}
如果我輸入:
11
11
13
13
13
14
我認為它應該像這樣執行:
當我輸入
11 11
控制台應顯示“11次發生2次”。
然后我可以繼續輸入
13 13 13
然后控制台應顯示“13次發生3次”。
但結果是只有當我輸入所有數字后,控制台才輸出一次結果。 為什么?
謝謝你的幫助 。
來自終端的輸入是線路緩沖的。
第一個std::cin >> currVal
阻塞,直到輸入在標准輸入處可用。
直到您按<Enter>
鍵才會發生這種情況。 (在<Enter>
,您輸入的字符仍然位於終端/ CMD框的行緩沖區中。您可以退格,編輯等;只有當您按<Enter>
,終端/ CMD框才會實際發送那些程序標准輸入的字符。)
為了實現預期的行為,請嘗試在每個數字后按<Enter>
。
樣本中的std::cin >> currVal
都會阻塞標准輸入, std::cin
表示來自標准輸入的值,在這種情況下,鍵盤是標准輸入。
要確認鍵盤的輸入,您需要按Enter
鍵,然后從鍵盤的buffer
中刪除值並由您的代碼處理。
如果你想獲得每次按鍵的值,你需要使用類似std::getchar
東西,該函數會像你期望的那樣立即讀取緩沖區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.