【问题标题】:How can I check if a string is a whole number in C?如何检查字符串是否是C中的整数?
【发布时间】:2020-07-13 06:55:16
【问题描述】:

我最近遇到一个问题,我有一个由argv[]输入的字符串数组来检查它是否为整数。

我尝试使用isdigit()。但是,它会以整数形式返回 "20x"。我搜索了很多,但找不到任何对 C 语言有帮助的东西。

提前谢谢你!

【问题讨论】:

  • 你看过atoi()吗?
  • 是的,我有,atoi 在“20x”中使用时仍然接受它作为整数值“20”
  • 确保字符串以 null 结尾,并在每个字符上使用 isdigit 对其进行迭代。如果您确实需要将字符串转换为int,请不要这样做。只需使用strtol(或其同级函数之一)并尝试转换并检查错误。不要使用atoi,因为它不能报告错误。
  • isdigit 检查 character 是否为 digit。您必须遍历字符,并为每个字符检查它是否是数字。
  • 这实际上非常困难。听起来很滑稽,这取决于您所说的数字是什么意思!数字比开箱即用的 C 类型所能表示的要多一点。例如,1.000 + 0i 是一个整数,但解析起来很麻烦。然后,您必须绕过 C 中令人讨厌的前导零表示八进制常量的约定,因此需要避免使用例如会抛出 08 的技术。那么,您到底需要什么?

标签: c arrays string algorithm


【解决方案1】:

[需要stdbool.hctype.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;
}

这也适用于大整数。

我希望您了解处理此任务的逻辑和方法。只需遍历字符串中的每个字符并根据需要对其进行验证。

【讨论】:

  • 领先的-怎么样?
  • @Ackdari 整数没有前导 -。也许你把问题误认为整数了。
  • 根据wikipedia,这个词是含糊的。但是是的,似乎是这样。
  • @Ackdari 哈哈,我明白了。甚至整个问题都是模棱两可的,因为 OP 没有对输入字符串给出明确的描述。好吧,如果有人也需要忽略尾随的减号,那么将 if (*num == '+') 更改为 if (*num == '+' || *num == '-')
【解决方案2】:

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

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, .....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多