[英]How to check input in command line is integer in C?
I want the code to check input in command line is integer.我希望在命令行中检查输入的代码是整数。 ie 10b is not valid.
即 10b 无效。 I tried isdigit() but is not working?
我试过 isdigit() 但不起作用? Thanks in advance.
提前致谢。
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
int key = atoi(argv[1]);
if (isdigit(key))
{
printf("Success\n\%i\n", key);
exit(0);
}
}
printf("Usage: ./caesar key\n");
return 1;
}
Function isDigit
checks if a single character is a digit, ie in the range between '0'..'9'
.函数
isDigit
检查单个字符是否为数字,即在'0'..'9'
之间的范围内。 To check if a string is a number, I'd suggest to use function strtol
.要检查字符串是否为数字,我建议使用函数
strtol
。
long strtol(const char *str, char **str_end, int base )
converts a string str
to an integral number and also sets the pointer str_end
to the first character that took not part in the conversion any more. long strtol(const char *str, char **str_end, int base )
将字符串str
转换为整数,并将指针str_end
设置为不再参与转换的第一个字符。 If you require that no characters must follow your number, then str_end
must point to the string's end, ie to string termination character '\\0'
:如果您要求数字
str_end
不能有任何字符,则str_end
必须指向字符串的结尾,即字符串终止字符'\\0'
:
#include <stdio.h>
#include <stdlib.h>
int isNumber(const char* str) {
if (!str || *str=='\0') { // NULL str or empty str: not a number
return 0;
}
char* endOfNum;
strtol(str,&endOfNum,10);
if (*endOfNum == '\0') { // string is at its end; everything in it was a valid part of the number
return 1;
} else {
return 0; // something that is not part of a number followed.
}
}
int main() {
const char* vals[] = {
"10b",
"-123",
"134 ",
" 345",
"",
NULL
};
for (int i=0; vals[i]; i++) {
printf("testing '%s': %d\n", vals[i], isNumber(vals[i]));
}
}
Output:输出:
testing '10b': 0
testing '-123': 1
testing '134 ': 0
testing ' 345': 1
testing '': 0
Adapt the meaning of corner cases like empty strings or NULL-strings to your needs.根据您的需要调整特殊情况(如空字符串或 NULL 字符串)的含义。
My first thought would be to use something like:我的第一个想法是使用类似的东西:
int inputvalue = 0;
if (sscanf(argv[i], "%d", &inputvalue) == 1)
{
// it's ok....
}
else
{
// not an integer!
}
or something like that.或类似的东西。 See http://www.cplusplus.com/reference/cstdio/sscanf/
见http://www.cplusplus.com/reference/cstdio/sscanf/
The isdigit
function checks whether a single character represents a single digit. isdigit
函数检查单个字符是否代表单个数字。 (numbers − 0 1 2 3 4 5 6 7 8 9). (数字 - 0 1 2 3 4 5 6 7 8 9)。
In order to check if a string is an integer you could use a function like that.为了检查字符串是否为整数,您可以使用这样的函数。 It will
它会
bool isNumber(char number[])
{
int i = 0;
// only if you need to handle negative numbers
if (number[0] == '-')
i = 1;
for (; number[i] != 0; i++)
{
if (!isdigit(number[i]))
return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.