Reputation: 1
I want to be able to continue using inputs after I have made an error while inputting a value using 'std::cin >>'.
After putting a character into an integer variable, for instance, all other statements in the source that use the cin function stop working.
Is it possible to continue using cin after creating an error?
#include <iostream>
using namespace std;
int addition(){
int sum = 0, val = 0;
while(cin >> val){
sum += val;
}
return sum;
}
int multiplication(){
int x = 0, y = 0;
cin >> y;
x = y;
while(cin >> y){
x = x * y;
}
return x;
}
int main()
{
int x = addition();
int y = multiplication();
return 0;
}
Upvotes: 0
Views: 667
Reputation: 129364
If it's an error because you tried to read an integer and got some "non-number" character, you need to use cin.clear()
to clear the error, then cin.get()
or similar to remove the offending character(s). If you have received an end-of-file
, it's much harder, since that tends to "stick" in some implementations - so, basically, if you hit an end of file, it's game over unless you jump through some really nasty hoops (writing your own streambuf
seems to be one solution, but but that's about as pleasant as sticking red hot needles in your eyes, I've been told - never really tried either...).
There are many alternative solutions, such as reading a string, and then trying to translate that to numbers, or reading a character at a time, and doing your own translation, or using some ready-made library that translates for you. None of these are guaranteed to allow you to continue if the user hits the "end-of-file" key (CTRL-Z in Windows and some others, CTRL-D in Linux/Unix/MacOS X and related - not sure about MacOS before X, but does anyone still care?)
Upvotes: 3
Reputation: 63471
You just need to read the character out and try again.
while( !(cin >> y) && !cin.eof() )
{
cin.get(); // Skip invalid character
}
This is a little unusual. What we would normally expect is to output an error. If values are being entered at the prompt, we tend to use getline
instead and then parse the result:
while(1)
{
string line;
if( getline(cin, line) )
{
istringstream iss(line);
if( iss >> y ) {
break;
} else {
cerr << "Invalid input. Try again.\n";
}
} else {
cerr << "End of stream\n";
break;
}
}
Upvotes: 0