确定C字符串是否是C中的有效int

sar*_*ara 19 c string validation int

我需要检查一个C字符串是否是一个有效的整数.

我试过了两个

int num=atoi(str);
Run Code Online (Sandbox Code Playgroud)

int res=sscanf(str, "%d", &num);
Run Code Online (Sandbox Code Playgroud)

但是"8 -9 10"在两行中发送字符串只返回8,而没有指出该字符串的无效性.

有人可以建议替代方案吗?

blu*_*ift 30

看看strtol(),它可以通过指针返回告诉你字符串的无效部分.

并提防热心的示例代码..请参阅手册页以获得全面的错误处理.

  • 注意`strtol()`返回一个`long`结果.如果要检查有效的`int`,还需要检查结果是否在"INT_MIN".."INT_MAX"范围内. (4认同)
  • 好吧,你是对的我只是注意到她指定了C字符串. (2认同)

asv*_*kau 7

也许我会因为没有使用strtol或类似libc功能而受到抨击,但对这个问题的推理并不那么难:

#include <stdbool.h>  // if using C99...  for C++ leave this out.
#include <ctype.h>

bool is_valid_int(const char *str)
{
   // Handle negative numbers.
   //
   if (*str == '-')
      ++str;

   // Handle empty string or just "-".
   //
   if (!*str)
      return false;

   // Check for non-digit chars in the rest of the stirng.
   //
   while (*str)
   {
      if (!isdigit(*str))
         return false;
      else
         ++str;
   }

   return true;
}
Run Code Online (Sandbox Code Playgroud)

[注意:我可能已经做isdigit(*str++)了其他事情,而不是else保持缩短但我的回忆是标准说它可能isdigit是一个宏.]

我猜一个限制是,如果字符串中的数字不适合整数,则不会返回false.这对你来说可能或不重要.

  • @asveikau:所以,这将接受''-37'`但它会拒绝`'+ 42'`? (6认同)
  • “没那么难”,但是您必须回来更改它;) (2认同)
  • @blueshift 点已采纳,但在 Web 表单中输入代码时 5 分钟内进行 1 次编辑对我来说并不是那么糟糕。:-) (2认同)