【问题标题】:C - convert from string to unsigned intC - 从字符串转换为无符号整数
【发布时间】:2016-02-24 17:43:16
【问题描述】:

如何将字符串转换为无符号整数?

我知道strtoul() 从字符串转换为unsigned long int,但我想要普通的int 而不是long int

我还没有找到能做到这一点的函数。

【问题讨论】:

  • atoi 但它没有错误检查与 strtoul 有相同的方式。您可以使用strtoul 并检查该值是否小于或等于UINT_MAX
  • @BLUEPIXY: sscanf 不一定对小于 long 的类型执行正确的范围检查。
  • 是的,标准没有指定 ERANGE 错误。(使用 GCC)
  • @NorbertvanNobelen:这个问题是关于 C,而不是关于 C++。

标签: c converter type-conversion unsigned-integer


【解决方案1】:

刚刚测试并发现strtoul 转换为等于UINT_MAX 的值,所以我猜这可行。

【讨论】:

  • 可能是因为您在 Windows 上编程。在这个平台上sizeof(unsigned int) == sizeof(unsigned long),所以strtoul 确实可以完成这项工作。在更一致的 64 位平台上,alk 的解决方案要优越得多。
【解决方案2】:

但我想要普通的 [unsigned] int 而不是 long [unsigned] int。

您想使用strtoul(),将其分配给long unsigned int,测试结果是否在[0..UINT_MAX] 的范围内,如果是这种情况,请将long unsigned int 分配给unsigned int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    相关资源
    最近更新 更多