c++ - 如何检查从 C++ 字符串到 unsigned int 的转换

标签 c++ casting type-conversion

我需要:

1) 找出我当前系统上的最大 unsigned int 值是多少。我没有在 limits.h 上找到它。编写 unsigned int maxUnsInt = 0 - 1; 是否安全?我还尝试了返回正确值的 unsigned int maxUnsInt = MAX_INT * 2 + 1,但编译器显示有关 int 溢出操作的警告。

2) 找到后,检查 C++ 字符串(我知道它仅由数字组成)是否超过我系统上的最大无符号整数值。

我的最终目标是当且仅当字符串是有效的无符号整数时,使用 atoi 将字符串转换为无符号整数。我宁愿只使用标准库。

最佳答案

应该有一个 #define UINT_MAX<limits.h> ;我会 如果没有,我会很惊讶。否则,它保证 那:

unsigned int u = -1;

将产生最大值。在 C++ 中,您还可以使用 std::numeric_limits<unsigned int>::max() ,但直到 C++11, 那不是一个完整的常量表达式(可能或可能 不是问题)。

unsigned int u = 2 * MAX_INT + 1;

不保证是任何东西(至少在一个系统上, MAX_INT == UMAX_INT ).

关于检查字符串,最简单的解决方案是 是要用strtoul ,然后验证 errno和返回值:

bool
isLegalUInt( std::string const& input )
{
    char const* end;
    errno = 0;
    unsigned long v = strtoul( input.c_str(), &end, 10 );
    return errno == 0 && *end == '\0' && end != input.c_str() && v <= UINT_MAX;
}

如果您使用的是 C++11,您还可以使用 std::stoul , 哪个 抛出 std::out_of_range溢出时的异常。

关于c++ - 如何检查从 C++ 字符串到 unsigned int 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893264/

相关文章:

azure - 如何将秒转换为格式 HH :mm:ss in Kusto

c++ - 在这种情况下使用 string_view 会导致不必要的字符串复制吗?

c++ - 如果不使用 pthread_join(),为什么从特定线程打印两次 'cout' 语句(即使已同步)?

java - 从列表转换为集合

c++ - 从 std::shared_ptr<void> 初始化 std::shared_ptr<T>

java - 使用泛型来替换特定的类类型

c++ - 表达式必须具有整数或枚举类型

java - 什么特性对应于 Java 中的 'synchronized'?

c - 结构和指针错误 : dereferencing pointer to incomplete type

string - Perl $strings 到哈希表的转换