简体   繁体   English

C中的整数输入检查

[英]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. 我想问一下在C中检查用户输入的最有效方法是什么。我希望用户输入4位整数。 How can I make sure that the user has entered exactly 4 digits and no letters? 如何确保用户输入的数字准确无误是4位数字?

One way: 单程:

1) read as string or char* 1)读取为stringchar*

2) check each char falls within 49-58 ASCII range. 2)检查每个字符是否在49-58 ASCII范围内。

Finally, convert into int using atoi() (or atol() in case of long) if there are only four chars in the string and satisfy (2) 最后,如果字符串中只有四个字符并满足(2),则使用atoi()转换为int atoi()如果是long则转换为atol())

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. 您可以做的是检查lengh是否小于4,如果是,则循环并为每个字符使用isdigit()以查看是否为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函数将您的字符串转换为long strtol can do error checking to check you really got a long . strtol可以进行错误检查以检查您是否真的很long Then check the number is between 1000 and 9999 (for positive 4-digits decimal integers). 然后检查数字在10009999之间(对于4位正整数十进制整数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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