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

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

我试过了两个

int num=atoi(str); 

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

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

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

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

并注意热情的示例代码..请参阅手册页以获得全面的error handling。

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

 #include  // if using C99... for C++ leave this out. #include  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。 这对你来说可能或不重要。

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

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

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

?[ – +] [0-9] +

以及浮点数的一般情况:

[+ – ] [0-9] + [0-9] *([EE] [ – +] [0-9] +?)?[。]?

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

 #include  ..... 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"; 

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

可以使用类似的东西:

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

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

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