1

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?

4
  • 1
    for(int i=0;i<4;++i)if(!isdigit(in[i])) panic(); if(in[4]) panic(); ;-) Commented Apr 2, 2012 at 21:12
  • I thought to subtract the number 999 from the integer, because if the user has added a letter in the input C will neglect it and will save a three digit integer. then I check if the output it's positive or negative Commented Apr 2, 2012 at 21:14
  • Get input from the user as a string. Loop over the string and check that each character is an integer using isdigit from <ctype.h> Commented Apr 2, 2012 at 21:15
  • Can the integer value start with leading zeros? Commented Apr 3, 2012 at 1:51

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

4 Comments

@MichaelKrelin-hacker a string. A data format as defined in the C Standard in 7.1.1p1 (C99)
Don't check for the range 49-58; use '0' - '9', or better yet call isdigit((unsigned char)s[i]).
Well, char * in C is called of string too
@ouah, "a string" or `string'? ;-)
1

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;
 }

Comments

0

Use strtol function to convert your string to a long. strtol can do error checking to check you really got a long. Then check the number is between 1000 and 9999 (for positive 4-digits decimal integers).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.