So...here is my code that refer to C++ Primer 1.4.4 section.
#include <iostream>
int main()
{
int currVal = 0, val = 0;
if (std::cin >> currVal) {
int cnt = 1;
while (std::cin >> val) {
if (val == currVal) {
++cnt;
} else {
std::cout << currVal << " occurs "
<< cnt << " times." << std::endl;
currVal = val;
cnt = 1;
}
}
std::cout << currVal << " occurs "
<< cnt << " times." << std::endl;
}
return 0;
}
I have to admit that the simple program basically work normally. But for the further discussion, I'd like refer to a asciinema
recording in the first place.
In the recording I run ./a.out
three times. In the first time, I typed numbers and press enter the first two recording printed and only after ctrl + D was pressed the third (last) result was printed. From previous sections in the book, I know ctrl + D is used to feed some symbols to stop the while loop. But I really wonder if it (ctrl + D here cause a strange stop) works just like as same as authors' expectation for there is no mention on how keys was pressed exactly about that example in the book.
In the last two runs, my first approach is press ctrl + D (the first result printed) and enter (the second result printed), then following several enters (no respond except more lines). Lastly, I pressed ctrl + D (the third result printed).
My last approach is press ctrl + D for two times. The first result printed on the first press and the last two came out on the second press.
With these two runs comes my confusing that after press ctrl + D (I think) there should be a stopping signal in the end of cin
stream. So why did the while
loop not stop? I'd appreciate a lot if anyone can explain the process behind it.
My working environment is urxvt
on Manjaro Linux
with zsh
and oh-my-zsh
installed.