C++ tip: Check if input is of valid data type using cin.fail()

When accepting user inputs in C++ console applications using cin object, it is always a good idea to check the input stream for possible errors.

If you intend to read a numeric value using cin and the user inputs a character or string instead then it can lead to unexpected results and run-time errors later in program.

For example if you are using a do…while loop to implement a menu driven program, and instead of a numeric choice the user accidentally (or maliciously?) enters a character, your program can run into an infinite loop.

cin.fail() returns true if the input stream encounters errors, most commonly which happens due to reading incorrect data type.

Here is how you can prevent it:

 int i;
 cin>>i;
if(cin.fail()) {
  // do error handling here
}

You can also check for cin.fail() using the shortcut method :

if(!cin) {
  // this is same as cin.fail()
}

When cin fails, it is also very important to clear the input stream of any garbage value and reset the internal error flags. It can be done using the cin.clear() and cin.ignore() methods as follows :

if(!cin) {
 cin.clear(); // clears error flags
 cin.ignore(999,'\n'); // the first parameter is just some arbitrarily large value, the second param being the character to ignore till 
}

Putting it all together

Here is a more robust way to read any input from user which uses the functions cin.ignore() and cin.clear() :

 int i;
 while(!(cin>>i)) {
 	cin.clear();
 	cin.ignore(999,'\n');
 	cout<<"Invalid data type! Please enter 'i' again";
 }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2018 All rights reserved | Powered by WordPress
Back to top
Theme by dynamicguru.com