Do not allow the user to type letters in the cin input

Hi, what code do you use to make it so the user is not physically able to type letters in the input for a cin statement , only numbers, and vise-versa?
Under the "conio" header (include the .h if you use it), there is a function called "getch()" that holds the character the user types in. This will allow you to grab characters one at a time and test whether they are letters or numbers.

Warning, there are keys which will send two hexadecimal numbers because of their specialty, so getch will grab the first number and the second number will be sent to the following getch or cin. In some special cases, the numbers these keys send might end up matching with the hexadecimal number of a letter, giving a false positive in your tests.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <limits>

using std::cin;
using std::cout;
using std::endl;
using std::numeric_limits;
using std::streamsize;

int main() {
   int num;
   cout << "Enter a number, please: ";
   cin >> num;
   if(cin.fail()) { // check if cin failed to parse the input correctly
      cin.clear(); // clear the error flags
      cin.ignore(numeric_limits<streamsize>::max(), '\n'); /* ignore the rest of what's left in the input buffer
                                                               because cin stops reading at the first bad character*/
      cout << endl << "That wasn't a number D:" << endl;
      return 0x00000BAD;
   }
   cout << endl << "num = " << num << endl;
   return 0;
}
Last edited on
Thanks Guys!
Topic archived. No new replies allowed.