|
-
June 23rd, 2008, 06:59 PM
#1
Catching Input error
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:
Code:
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!
-
June 24th, 2008, 02:00 AM
#2
Re: Catching Input error
You could do something along these lines:
Code:
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:
Code:
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|