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

Feb 9, 2013 at 4:11am
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?
Feb 9, 2013 at 7:22am
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.
Feb 9, 2013 at 7:41am
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 Feb 9, 2013 at 7:45am
Feb 10, 2013 at 1:50am
Thanks Guys!
Topic archived. No new replies allowed.