如何使用`strtoul`来分析字符串,其中零可能是有效的? [英] How to use `strtoul` to parse string where zero may be valid?

查看:150
本文介绍了如何使用`strtoul`来分析字符串,其中零可能是有效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据strtoul的文档,有关其返回值...

According to the documentation for strtoul, regarding its return value...

此函数将转换后的整数返回为long int值.如果无法执行有效的转换,则返回零值.

This function returns the converted integral number as a long int value. If no valid conversion could be performed, a zero value is returned.

如果我解析用户提供的字符串"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解析可能为零的字符串?

How to use strtoul to parse string where zero may be valid?

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`来分析字符串,其中零可能是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆