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
You cannot restrict what user types on the keyboard. You can accept it as std::string
and use boost::lexical_cast
to convert it to your expected number type and catch and process boost::bad_lexical_cast
exception.
You cannot force the user to give correct input. But you can ask them to give another input if previous was invalid. There are different procedures to do so. One is the following:
This is alright and quite common. It uses dynamic memory though. Another option would be:
cin >> value;
like you normally docin.fail()
to see if input was correctly read (check for cin.eof()
also)If failed, ignore all input until whitespace:
char c;
while (cin >> c)
if (isspace(c))
break;
This has the added advantage that in an erroneous input like this:
abc 12.14
you don't ignore the whole line, but just the abc
.
Here's some pseudo code;
double num;
while( num != realNum) //check input is valid
{
cin >> num;
}
....
double number
if (cin >> number) {
do_stuff_with(number);
} else {
std::cerr << "That wasn't a number!";
}
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 <typename T> // 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 !
You can use regex to solve it
double inputNumber()
{
string str;
regex regex_double("-?[0-9]+.?[0-9]+");
do
{
cout << "Input a positive number: ";
cin >> str;
}while(!regex_match(str,regex_double));
return stod(str);
}
Remember that include regex library in the header.