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或类似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.这对你来说可能或不重要.