问题描述
根据strtoul
的文档,有关其返回值...
According to the documentation for strtoul
, regarding its return value...
如果我解析用户提供的字符串"0",对于我的应用程序来说,"0"可能是有效条目,该怎么办?在那种情况下,我似乎无法通过使用strtoul
来确定是否执行了有效的转换.还有另一种方法可以解决这个问题吗?
What if I'm parsing a user-supplied string of "0" where, for my application, "0" may be a valid entry? In that case it seems that I have no way to determine from using strtoul
if a valid conversion was performed. Is there another way to handle this?
推荐答案
从strtoul()
返回的任何值都可能来自预期的字符串输入,或者来自 other 的非预期字符串.进一步的测试很有用.
Any value returned from strtoul()
may be from an expected string input or from other not so expected strings. Further tests are useful.
以下字符串均从strtoul()
- 确定
"0"
,"-0"
,"+0"
- 不正常
""
,"abc"
- 通常认为还可以:
" 0"
- 可以还是不可以,具体取决于目标:
"0xyz"
,"0 "
,"0.0"
- OK
"0"
,"-0"
,"+0"
- Not OK
""
,"abc"
- Usually considered OK:
" 0"
- OK or not OK depending on goals:
"0xyz"
,"0 "
,"0.0"
strtoul()
具有多种检测模式.
int base = 10;
char *endptr; // Store the location where conversion stopped
errno = 0;
unsigned long y = strtoul(s, &endptr, base);
if (s == endptr) puts("No conversion"); // "", "abc"
else if (errno == ERANGE) puts("Overflow");
else if (*endptr) puts("Extra text after the number"); // "0xyz", "0 ", "0.0"
else puts("Mostly successful");
尚未检测到的内容.
-
负输入.
strtoul()
有效地环绕strtoul("-1", 0, 10) == ULONG_MAX)
. 通常在粗略的文档审阅中都会遗漏此问题.
允许前导空白.
还要检测负值:
// find sign
while (isspace((unsigned char) *s)) {
s++;
}
char sign = *s;
int base = 10;
char *endptr; // Store the location where conversion stopped
errno = 0;
unsigned long y = strtoul(s, &endptr, base);
if (s == endptr) puts("No conversiosn");
else if (errno == ERANGE) puts("Overflow");
else if (*endptr) puts("Extra text after the number");
else if (sign == '-' && y != 0) puts("Negative value");
else puts("Successful");
这篇关于如何使用`strtoul`来分析字符串,其中零可能是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!