night_hawk
night_hawk

Reputation: 101

How to catch a run-time error in c++?

I have a problem with being able to take care of run-time errors where the user types in data different than the one expected. For example, an integer is expected, but (maybe) the user enters a string. In my console programs, when this happens, I just get a whole lot of junk printed on my screen, it goes into infinite loop. How can I take care of this, such that an error message is displayed when this happens, instead of the whole program going to trash?

int x = 0;
cout << "\n\nEnter a number(1-9): ";
cin >> x;
if(x<1 || x>9)
{
   cout<<"\nThe place you entered is invalid. Please enter the correct place number";
}else{
   cout<<"Correct";
}

If i entered a number above than 2^31(i know its the maximum value for int datatype) or a char value it goes into a infinite loop. How can i catch solve this problme

Upvotes: 1

Views: 299

Answers (1)

templatetypedef
templatetypedef

Reputation: 373492

cin is a bit weird in that if you try to read data from the user and the type is wrong (for example, you enter a string when an int is expected) or the value is illegal (for example, it's too big), cin enters a "fail state" and from that point forward will refuse to read any values from the user until you explicitly fix the problem. Properly reading data from cin such that this doesn't happen is a bit tricky, but can be simplified by just writing some nice helper routines once and calling them in your later programs.

For a description of one approach for properly reading data from cin, you might want to check out these course notes from Stanford's CS106L course that describe how streams work in C++ and how to properly read and write data.

Hope this helps!

Upvotes: 2

Related Questions