I'm a beginner of C++,while reading the book 《C++ Primer》 5th,I'm a little confused in chapter 1.4.4. when I run the program in 1.4.4,here is the step in my computer:
#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;
}
- type the numbers:42 42 42 42 42 55 55 62 100 100 100
- type
Ctrl+D
- the program run by itself(not waitting me to input Enter)
- output the answer:
42 occurs 5 times
55 occurs 2 times
62 occurs 1 times
- secondly type
Ctrl+D
- output the remained answer
100 occurs 3 times
my question is why I have to input second times of Ctrl+D,my code environment is Ubuntu+GCC,I also run it in VS2013,it only needs to input once Ctrl+D.
I've searched in stackoverflow,but I didn't got my answer.
Incorrect output. C++ primer 1.4.4
confused by control flow execution in C++ Primer example
C++ Primer fifth edtion book (if statement) is this not correct?