简体   繁体   中英

integer input check in C

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?

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)

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM