C++ Number input validation
I need to validate a开发者_开发百科 user input using getch()
only to accept numeric input
`int input_put=getch();`
if(input >=0 && < 9){
}else{
}
To best accept numeric input, you have to use std::cin.clear() and std::cin.ignore()
For example, consider this code from the C++ FAQ
#include <iostream>
#include <limits>
int main()
{
int age = 0;
while ((std::cout << "How old are you? ")
&& !(std::cin >> age)) {
std::cout << "That's not a number; ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You are " << age << " years old\n";
...
}
This is by far, the best and the cleanest way of doing it. You can also add a range checker easily.
The complete code is here.
if(input >= '0' && input <= '9')
or:
if(isdigit(input))
getch
returns a character code. The character code for "0" is 48, not 0, although you can get away with using a character constant instead (since char constants are really integer constants) and that will be more readable. So:
if (input >= '0' && input <= '9')
If you're using Visual C++ (as your tags indicate), you may find the MSDN docs useful. For instance, you probably should be using _getch
instead, or _getchw
if you want to write software that can be used more globally. And in that same vein, you probably want to look at isdigit
, isdigitw
, and the like.
精彩评论