Dealing with a Failed Input Stream

It took two days of research and a lot of thinking to come up with the sample code in Listing 5.1. But, since you only have 10 minutes, let's dive right into it.

Listing 5.1. Getting Numeric Input and Recovering from an Error
 1: #include <iostream> 2: 3: using namespace std; 4: 5: int main(int argc, char* argv[]) 6: { *7: int ReturnCode = 0; 8: 9: float Dividend = 0; 10: cout << "Dividend: "; 11: cin >> Dividend; 12: *13: if (!cin.fail()) // Dividend is a number *14: { 15: float Divisor = 1; 16: cout << "Divisor: "; 17: cin >> Divisor; 18: 19: float Result = (Dividend/Divisor); 20: cout << Result << endl; *21: } *22: else // Dividend is not a number *23: { *24: cerr << "Input error, not a number?" << endl; ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND 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.