O'Reilly logo

SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION by Jesse Liberty

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

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; ...

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