I would like to ask you what's the most efficient way for checking user's input in C. I want the user to enter a 4 digit integer. How can I make sure that the user has entered exactly 4 digits and no letters?
3 Answers
One way:
1) read as string or char*
2) check each char falls within 49-58 ASCII range.
Finally, convert into int using atoi() (or atol() in case of long) if there are only four chars in the string and satisfy (2)
4 Comments
ouah
@MichaelKrelin-hacker a string. A data format as defined in the C Standard in 7.1.1p1 (C99)
Keith Thompson
Don't check for the range 49-58; use
'0' - '9', or better yet call isdigit((unsigned char)s[i]).Jack
Well,
char * in C is called of string tooMichael Krelin - hacker
@ouah, "a string" or `string'? ;-)
All input are taken as strings(console). what you can do is check if lengh is less than four, if so loop through and use isdigit() for each char to see if is digit.
For checking numeric you can do something like like:
int isnumeric(char *str)
{
while(*str)
{
if(!isdigit(*str))
return 0;
str++;
}
return 1;
}
isdigitfrom<ctype.h>