This code works fine if I enter something that isn't a number in, e.g. F
: it will print the error message. However, if I enter e.g. 2F2
or , it will take the 2
and pass the check, continue in my code and on the next cin >>
statement it will put the F
in, and then it loops back and puts the 2
in.
How do I make it so it only accepts a single number e.g. 2
and not e.g. 2F2
or 2.2
?
int bet = 0;
// User input for bet
cout << " Place your bet: ";
cin >> bet;
cout <<
// Check if the bet is a number
if (!cin.good())
{
cin.clear();
cin.ignore();
cout << endl << "Please enter a valid number" << endl;
return;
}
bool Checknum(std::string line) {
bool isnum = true;
int decimalpoint = 0;
for (unsigned int i = 0; i < line.length(); ++i) {
if (isdigit(line[i]) == false) {
if (line[i] == '.') {
++decimalpoint; // Checks if the input has a decimal point that is causing the error.
}
else {
isnum = false;
break;
}
}
}
if (decimalpoint > 1) // If it has more than one decimal point.
isnum = false;
return isnum;
}
If you take a string from the user, this should work. You can convert the string to an integer or a float(stoi or stof, respectively). It may not be the best solution there is, but this is what I have. Excuse the indentation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments