-
Char or Number
How would u be able to find out if a person entered a number instead of a character and raise an error if they entered a character?
For example u want the person to be able to enter only a number not a letter, how do u know if they entered a letter?
thanks:D :D
-
if char's number is between 48 and 57 then it is a number..else it isnt
-
also c++ should have some string manip. library that has some isAlpha or isDigit function like all programming languages have
-
so u have to store the number in a char data type?
-
Several ways:
C:
1) Read in a string (fgets, scanf, ...) and check every character of the string for its number-being with isdigit from <ctype.h>.
2) Read in an integer with scanf and check the return value. For example if you write
int num;
int read = scanf("%i", &num);
and read is < 1 then the user didn't enter a number.
C++:
1) See C1, but using the locale-sensitive versions of the type functions. Either in <string> or in <locale>, not sure.
2) cin fails if it doesn't read a number:
int num;
cin >> num;
if(!cin.good())
then something happened, most likely a format error. You can also set cin to throw an exception should such a thing occur.