tags:

views:

71

answers:

3

I need to validate a user input using getch() only to accept numeric input


`int input_put=getch();`

    if(input >=0 && < 9){ 

}else{


}
+1  A: 

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.

T.J. Crowder
thanks this works but i can only take one user input Also in the if() how can i get numbers like 10000 ?
Sudantha
@Sudantha: If you really, really need to be using `getch` for this, then you'll have to loop until you receive a character you define as being an "end" of the input (carriage return, for instance). If this is homework, then that's probably want your instructor is trying to teach you, looping with a terminal condition. If it's not, the odds are very high indeed that you want to use a different input mechanism.
T.J. Crowder
thanks for the help and its not homework ;)
Sudantha
+2  A: 
if(input >= '0' && input <= '9')

or:

if(isdigit(input))
PigBen
+3  A: 

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.

sukhbir
sukhbir
Never mind, now's not the time for me to learn more about C++ streams. In fact, I'm rather hoping the day never comes. :-)
T.J. Crowder
@T.J.: Please, tell me if I am wrong! You deleted your comment. I am here to learn only.
sukhbir
Aah ok. In fact, I also read this on the C++ FAQ. It is not my code.
sukhbir
@PulpFiction: Yeah, I think my comment was based in ignorance, so I'm going to stop wasting your time now. :-)
T.J. Crowder