How do you determine whether the input is a string, a double type or integer?
The state of cin will tell you if there was an error. If you ask for an integer, for example, and the operation fails, it's fairly safe to assume that the user typed the wrong thing. The conventional method is a loop that clears the stream state and discards remaining input every time this happens:
int x;
cout << "Please enter an integer value: ";
while (!(cin >> x)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: ";
}
cout << "The integer value was " << x << '\n'; The down side to this method is that if the user types something like "123foo", the "123" will be successfully read and the "foo" will be left in the stream. Depending on your needs, that could be undesirable.
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401