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

问题描述 投票:19回答:5

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

我试过了两个

int num=atoi(str);

int res=sscanf(str, "%d", &num);

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

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

c string validation int
5个回答
30
投票

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

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


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;
}

[注意:我可能会以其他方式完成isdigit(*str++)而不是else以保持更短但我的回忆是标准说isdigit可能是一个宏。]

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


2
投票

执行此操作的一种简单方法是读取int并确保其字符串表示形式与输入字符串相同,例如组合atoiitoa

int is_int(char const* p)
{
    return strcmp(itoa(atoi(p)), p) == 0;
}

0
投票

要检查字符串是否包含有效数字,可以使用正则表达式。例如对于整数使用:

[-+]?[0-9]+

以及浮点数的一般情况:

[+ - ]?[0-9] + [。] [0-9] *([eE] [ - +] [0-9] +)?

在C ++ 11的情况下,正则表达式函数在库中可用,例如“std :: regex_match(.....)”给出完全匹配。代码应该如下所示:

#include <regex>
.....
std::string strnumber("-1.234e+01");
float number;
if(regex_match(strnumber,std::regex("[+-]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?"))
number=std::stof(strnumber);
else
std::cout<<"error, string is not a valid number";

0
投票

很抱歉挖掘主题,但为了完整起见,因为这个帖子是进行谷歌搜索时的第一个匹配...

可以使用类似的东西:

ret = sscanf(string, "%d%n", &number, &idx);
if (ret == 0 || string[idx] != '\0')
    /* handle the error */

%n指令,根据手册页似乎是标准C,计算处理的字符数。

[编辑] sscanf似乎没有提供检测溢出的方法,所以strtoX函数族应该是首选恕我直言。

© www.soinside.com 2019 - 2024. All rights reserved.