How can I restrict the user to input real numbers only in C++ program?
Example:
double number; cin >> number;
and it won\'t accept t
I always use this code to request a specific type of input(Except strings and chars). The idea is to request any numeric type and use stringstream to see if it can be stored as the requested type, if not it will keep prompting the user until he inputs the requested type.
template // will not work with strings or chars
T forceInputType_T() {
T name;
bool check = false;
string temp;
while (check == false) {
cin >> temp;
stringstream stream(temp);
if (stream >> number) {
check = true;
} else {
cout << "Invalid input type, try again..." << endl;
}
}
return name;
}
If you want to use a Boolean then you could check every character in the string if it contains a number than return false and keep asking for an valid input with a loop !