confused by control flow execution in C++ Primer e

2019-05-18 20:51发布

问题:

I am going through C++ Primer (5th ed). In section 1.4.4, there is the following example:

#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;
}

When you run it with the given input 42 42 42 42 42 55 55 62 100 100 100

It prints

42 occurs 5 times

55 occurs 2 times

62 occurs 1 times

However, in order to get the final output line

100 occurs 3 times

you must press CTRL+D. Then that is printed and the program exits.

Why is this? To me, it looks like this last line should be printed and the program exited with the others. It seems I am misunderstanding how the control flow is executed so can someone please clarify?

ps I am aware of this Incorrect output. C++ primer 1.4.4 and C++ Primer fifth edtion book (if statement) is this not correct? However, neither of these explain WHY you must ctrl+d to print the final statement.

回答1:

That's because of this part:

while (std::cin >> val)

In order to terminate reading the input stream, you have to terminate it with an EOF, which is supplied by Ctrl-D.

Think about it: cin skips over whitespace by default and every time you enter a number you separate it with whitespace (a space, a tab or a newline).

How will the program ever terminate the input? The answer is when it reads an EOF character - which, as stated before, is supplied by Ctrl-D.



回答2:

You must press CTRL+D because otherwise the program does not know when your stdin stream has finished. It will otherwise just sit there at while (std::cin >> val forever without terminating.