O'Reilly logo

C++ Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Number-Reading Loops

You're preparing a program to read a series of numbers into an array. You want to give the user the option to terminate input before filling the array. One way is utilize how cin behaves. Consider the following code:

int n;
cin >> n;

What happens if the user responds by entering a word instead of a number? Four things occur in such a mismatch:

  • The value of n is left unchanged.

  • The mismatched input is left in the input queue.

  • An error flag is set in the cin object.

  • The call to the cin method, if converted to type bool, returns false.

The fact that the method returns false means that you can use non-numeric input to terminate a number-reading loop. The fact that non-numeric input sets an error flag means that you have to reset ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required