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 ...
Get The Waite Group's C++ Primer Plus, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.