Error/Disable String Input

Hey guys, I just have a quick question.
Say I have
double years;
cin>>years;

How would I generate an error/ reject the input if it was a string.
Thanks!
C++ does it for you. It generates an error AND rejects the input.

What you need to do is to check for the error C++ generated and decide what you're going to do with the input C++ rejected.

For example,

1
2
3
4
5
6
7
8
9
double years;
cin >> years;
if(!cin)  // was there an error?
{
    cin.clear();  // clear the error so that input can be re-processed
    string input;
    getline(cin, input); // process the previously rejected input
    cout << "Your input, " << input << " is not a valid double\n";
}
Last edited on
Ah thanks, I think I can make something work with the !cin.
Topic archived. No new replies allowed.