Click to See Complete Forum and Search --> : Catching Input error


xXshadowXx
June 23rd, 2008, 06:59 PM
Hi, I'm new to the forum, and I'm sorta new to programming, and I have a pretty simple question. (I hope)

I need to know how to handle an error when someone puts something other than a number into a double(like a letter)

Here's a small example:


double a;
cout << "Insert a number: ";
cin >> a;


This is where if a letter is inserted the program starts to flicker and crashes and stuff, if a letter is put in.

So, please someone show me how to catch the input error and maybe re-ask them for the value?

Thanks again!

laserlight
June 24th, 2008, 02:00 AM
You could do something along these lines:
double a;
for (;;)
{
cout << "Insert a number: ";
if (cin >> a)
{
break;
}
else
{
cout << "Sorry, invalid input.\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
The cin.clear() clears the error state of the stream so you can get input again. The cin.ignore() removes the incorrect input from the stream so that it will not be read again (unless the user happens to enter the same thing).

A simplified version, which might or might not amount to code obfuscation, would be:
double a;
while ((cout << "Insert a number: "), !(cin >> a))
{
cout << "Sorry, invalid input.\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
You could also simplify by writing a function and using it with a do while loop.