如何检查字符串在C中是否为整数?

如何检查字符串在C中是否为整数?,c,arrays,string,algorithm,C,Arrays,String,Algorithm,我最近遇到了一个问题,我让argv[]输入一个字符串数组来检查它是否是一个整数 我尝试使用isdigit()。但是,它返回的是一个整数“20x”。我搜索了很多,但找不到任何对C语言有用的东西 提前谢谢你 [需要stdbool.h和ctype.h] bool isWholeNumber(char* num) { // Check if the input is empty if (*num == '\0') return false; // Ignore the '+'

我最近遇到了一个问题,我让
argv[]
输入一个字符串数组来检查它是否是一个整数

我尝试使用
isdigit()
。但是,它返回的是一个整数
“20x”
。我搜索了很多,但找不到任何对C语言有用的东西


提前谢谢你

[需要
stdbool.h
ctype.h
]

bool isWholeNumber(char* num)
{
    // Check if the input is empty
    if (*num == '\0') return false;

    // Ignore the '+' sign if it is explicitly present in the beginning of the number
    if (*num == '+') ++num;

    // Check if the input contains anything other than digits
    while (*num)
    {
        if (!isdigit(*num)) return false;
        ++num;
    }

    // You can add other tests like
       // Ignoring the leading and trailing spaces
       // Other formats of whole number (1.0, 1.00, 001, 1+0i, etc.)
       // etc. (depends on your input format)

    // The input is a whole number if it passes these tests
    return true;
}
这也适用于大整数


我希望你了解完成这项任务的逻辑和方法。只需遍历字符串中的每个字符,并根据需要验证它们。

您可以检查字符数组中的每个字符:

for(int i = 0; i < length; i++){
   ch = charArray[i];
   if('0' <= ch && ch <= '9'){
      // it's a character number (in decimal)
   }
   // you do with other conditions: formated number, .....
}
for(int i=0;i如果('0'您看过
atoi()
?是的,我看过,atoi在“20x”中使用时仍然接受它作为整数值“20”,请确保字符串以null结尾,并在每个字符上使用
isdigit
对其进行迭代。如果您确实需要将字符串转换为
int
,则不要这样做。只需使用
strtol
(或其同级功能之一)然后尝试转换并检查错误。不要使用
atoi
,因为它不能报告错误。
isdigit
检查字符是否是数字。你必须循环检查字符,并为每个字符检查它是否是数字。这实际上非常困难。如果听起来不滑稽,这取决于你所说的数字!数字比开箱即用的C类型所能表示的要多一些。例如,
1.000+0i
是一个整数,但很难解析。然后你必须绕过C的恼人惯例,即前导零表示八进制常数,因此需要避免使用例如抛出08的技术。那么,你需要什么呢确切地说?前导的
-
怎么样?@Ackdari整数没有前导的
-
。也许你把这个问题错当成了整数。根据这个术语,是ambiguas。但看起来是这样。@Ackdari哈哈,我明白了。甚至整个问题都是模棱两可的,因为OP没有给出输入字符串的清晰描述。好吧,如果有人也需要忽略尾随的减号,然后将
if(*num='+')
更改为
if(*num='+'|*num='-')