The output is incomplete

I am just beginning to learn C++ with the book C++ Primer (5/e), I met this program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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;
}
I ran it on my PC with Code::Blocks, I inputted 42 42 42 42 42 55 55 62 100 100 100, then the output should be
1
2
3
4
42 occurs 5 times
55 occurs 2 times
62 occurs 1 times
100 occurs 3 times
However I saw only the first 3 lines
1
2
3
42 occurs 5 times
55 occurs 2 times
62 occurs 1 times
I tested many times, if some number is only inputted once, then the output will stop counting the next number.
Is something wrong with the program? This may be easy for you but some difficult for me, if you help me solve it out it would be very helpful and I'll be thankful.
The program will read numbers until it failed to read a number because you entered something that's not a number or because of EOF. It doesn't matter that you press enter. You can still enter more numbers. Press Ctrl-D (on Linux) or Ctrl-Z (on Windows), or just enter some character that is not a digit or whitespace to end the loop/program.
Topic archived. No new replies allowed.