问题
for example, if I enter "2a", it does not show an error nor asks the user to re-input the value. how do i fix this?
while (std::cin.fail())
{
std::cout << "ERROR, enter a number" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> dblMarkOne;
}
std::cout << "" << std::endl;
回答1:
Two possible solutions:
- First store the input in a std::string instead of directly to an int. Then, use strtol from for converting to an integer. If the endPtr points to 0, it means nothing is left at the end, so this is OK. Otherwise, some no number characters are found at the end
- In your example,
std::cin >> dblMarkOne;
will leave non-number characters instd::cin
, so if there is still data available instd::cin
after, for instance by usingstd::cin.peek()!=EOF
, this means the user has entered more than a number.
Edit : full tested code:
#include <iostream>
#include <cstdio>
int main(int argc, char ** argv)
{
bool ok = false;
int dblMarkOne;
std::cout << "Enter a number" << std::endl;
while (!ok)
{
std::cin >> dblMarkOne;
if(!std::cin.fail() && (std::cin.peek()==EOF || std::cin.peek()=='\n'))
{
ok = true;
}
else
{
std::cin.clear();
std::cin.ignore(256,'\n');
std::cout << "Error, Enter a number" << std::endl;
}
}
}
回答2:
One way would be to use the isDigit() function.
It returns a 1 for characters that are numbers in ascii and 0 otherwise.
How to use it would depend on whether you're expecting a single digit and are only checking that or want a longer number.
If you want to extract the number characters that occur until a non-number character occurs, store it to a char[] or std::string, then iterate over each character, either discarding characters you don't want or exiting at the first other character.
if you're only after a single digit, modify your loop to something like this:
std::cin >> dblMarkOne;
while (!isDigit(dblMarkOne)) {
std::cout << "ERROR, enter a number" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> dblMarkOne;
}
if you wanted a longer-than-one-digit number, just create a std::string to hold the input and iterate over its contents based on whether you want to break early or not, and store the output to your variable.
来源:https://stackoverflow.com/questions/18767800/c-fix-for-checking-if-input-is-an-integer