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;
Two possible solutions:
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:
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:
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.