#include <iostream>
int main()
{
usingnamespace std;
double a,b,c;
cin.unsetf(ios_base::skipws); // do not skip leading whitespace
cout << "Enter value of 'a': ";
// the '>>' always returns a cin object, which will be converted
// into a boolean using cin.good(). It indicates if an error happened.
if (!(cin >> a)) {
cin.clear(); // we have to clear error flags.
a = 5; // set default value
}
while (cin.get() != '\n'); // now remove all unpleasent input
cout << "Enter value of 'b': ";
if (!(cin >> b)) {
cin.clear();
b = 5;
}
while (cin.get() != '\n');
cout << "a + b = " << (c = a + b) << endl;
return 0;
}
alternativly you could do something like this.
1 2
cin >> a;
if (!cin.good()) { ... }
Just look in the web for cin error handling. The cin object does following things if an error happened (f.e. if you type an unexpected character for integer input):
Value a is left unchanged
The input is left in input queue
An error flag is set
I've tried your suggestion, but could not get any positive result.\
actually, i wish to do :
if an input value is asked by the user, and he just press "Enter" key, the program must ask the next input value and use the default set value for that input.