简体   繁体   中英

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')

要么:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM