C语言 C:检查命令行参数是否为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29248585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C: Checking command line argument is integer or not?
提问by 0aslam0
Signature of isdigit
签名 isdigit
int isdigit(int c);
Signature of atoi
签名 atoi
int atoi(const char *nptr);
I just wanted to check whether the command line argument passed was an integer or not.Here is the C Code:
我只是想检查传递的命令行参数是否为整数。这是 C 代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
if (argc == 1)
return -1;
printf ("Hai, you have executed the program : %s\n", argv[0]);
if (isdigit(atoi(argv[1])))
printf ("%s is a number\n", argv[1]);
else
printf ("%s is not a number\n", argv[1]);
return 0;
}
But the output is not as expected, when I am passing a valid number:
但是当我传递一个有效数字时,输出并不像预期的那样:
$ ./a.out 123
Hai, you have executed the program : ./a.out
123 is not a number
$ ./a.out add
Hai, you have executed the program : ./a.out
add is not a number
I couldn't figure out the error.
我无法弄清楚错误。
回答by niyasc
When you refer argv[1], it refers to a character array containing value 123. isdigitfunction is defined for a single character input.
So to handle with this situation, it is better to define a function as follows:
当您引用时argv[1],它指的是一个包含值的字符数组123。isdigit函数是为单个字符输入定义的。
所以为了处理这种情况,最好定义一个函数如下:
bool isNumber(char number[])
{
int i = 0;
//checking for negative numbers
if (number[0] == '-')
i = 1;
for (; number[i] != 0; i++)
{
//if (number[i] > '9' || number[i] < '0')
if (!isdigit(number[i]))
return false;
}
return true;
}
回答by R Sahu
if (isdigit(atoi(argv[1])))
will be:
将会:
if (isdigit(atoi("123")))
which will be:
这将是:
if (isdigit(123))
which will be:
这将是:
if ( 0 )
since 123represents the ASCII character '{'.
因为123代表 ASCII 字符'{'。
回答by mgarey
I thought I'd add something to the answers already here. In addition to checking for numbers in base 10, I thought it would be useful to check for and allow hexadecimal numbers as well. I also allow negative numbers.
我想我会在这里的答案中添加一些内容。除了检查以 10 为基数的数字之外,我认为检查并允许使用十六进制数字也很有用。我也允许负数。
I also added a few things to check for bad input (e.g. null pointer, letters inside of a string representing a decimal number, or invalid letters inside a string representing a hexadecimal number).
我还添加了一些内容来检查错误输入(例如,空指针、代表十进制数的字符串中的字母或代表十六进制数的字符串中的无效字母)。
Note that I use the to_lower(char c)function to ensure that letters representing hexadecimal will be lower case, just for convenience.
请注意,我使用该to_lower(char c)函数来确保表示十六进制的字母为小写,只是为了方便。
I return 1 (or true) if the string is a valid number, 0 if it isn't. If it is a valid number, I store the base inside the parameter base.
如果字符串是有效数字,则返回 1(或 true),否则返回 0。如果它是一个有效数字,我将基数存储在参数基数中。
// Return 1 if str is a number, 0 otherwise.
// If str is a number, store the base (10 or 16) in param base.
static int is_number(char *str, int *base)
{
// Check for null pointer.
if (str == NULL)
return 0;
int i;
int len = strlen(str);
// Single character case.
if (len == 1)
{
*base = 10;
return isdigit(str[0]);
}
// Hexadecimal? At this point, we know length is at least 2.
if ((str[0] == '0') && (str[1] == 'x'))
{
// Check that every character is a digit or a,b,c,d,e, or f.
for (i = 2; i < len; i++)
{
char c = str[i];
c = to_lower(c);
if (!(
(c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f')))
return 0;
}
*base = 16;
}
// It's decimal.
else
{
i = 0;
// Accept signs.
if (str[0] == '-' || str[0] == '+')
i = 1;
// Check that every character is a digit.
for (; i < len; i++)
{
if (!isdigit(str[i]))
return 0;
}
*base = 10;
}
return 1;
}
I used this function like this:
我这样使用这个函数:
int base, num;
if (is_number(str, &base)
num = strtol(str, NULL, base);
回答by Cherry
I don't know what isdigitexactly does, but due to name I think it should take a charargument, check for the char being a digit, is it?
我不知道究竟isdigit是什么,但由于名称,我认为它应该接受一个char参数,检查字符是否为数字,是吗?
I would write like this: (omitted the function shell, just show the core code)
我会这样写:(省略函数shell,只显示核心代码)
char* p = argv[1];
while (*p != '// Since There is an implicit conversion from const char* to std::string
// You May use this simplified version of the check_string instead
bool isNumeric(const string str)
{
// loop Through each character in the string
for(char x: str)
if(!isdigit(x)) // Check if a single character "x" its a digit
return false; // if its not return false
return true; // else return true
}
')
{
if (*p<'0' || *p>'9')
{
printf("%s is not a number", argv[1]);
return 0;
}
p++;
}
printf("%s is a number", argv[1]);
return 0;
回答by Chintan Patel
isdigit() function checks for a digit character ('0' to '9') which of course depends on ASCII values. Now value returned from your atoi does not fall within ASCII value between '0' to '9'. so it is showing that it is not a number.
isdigit() 函数检查数字字符('0' 到 '9'),这当然取决于 ASCII 值。现在从您的 atoi 返回的值不在“0”到“9”之间的 ASCII 值内。所以它表明它不是一个数字。

