Catching a string or char inputted for a double

How can I catch a string or char which is entered when I ask for a double?
1
2
3
4
5
6
7
8
9
double d;
if( cin >> d ){//if it isn't a number, cin will set an error flag and evaluate to false
   cout << "it's a double " << d << '\n';
}else{
   cin.clear();//you need to clear the error flag before you can do any input
   string str;
   getline(cin, str);
   cout << "it's a string " << str << '\n';
}
You could also take the input as a string and cast it to a double. I know that doesn't literally accomplish what you asked, but it could be handy depending on the next step you want to take with it. Just another option I thought was worth presenting.
Topic archived. No new replies allowed.