首页 > 解决方案 > C++ std::stoul 不抛出异常

问题描述

我有一个函数来检查字符串是否有效unsigned int

unsigned long int getNum(std::string s, int base)
{
    unsigned int n;
    try
    {
        n = std::stoul(s, nullptr, base);
        std::cout << errno << '\n';
        if (errno != 0)
        {
            std::cout << "ERROR" << '\n';
        }
    }
    catch (std::exception & e)
    {
        throw std::invalid_argument("Value is too big");
    }
    return n;
}

但是,当我输入诸如0xfffffffff(9 f's) 之类的值时,errno仍然为 0(并且不会引发异常)。为什么会这样?

标签: c++string-conversion

解决方案


让我们看看在 64 位机器上将0xfffffffff(9 f's)分配给 a 会发生什么。unsigned int

#include <iostream>

int main(){

    unsigned int n = 0xfffffffff; //decimal value 68719476735
    std::cout << n << '\n';

}

隐式转换将导致编译器发出警告,但不会导致异常。

的结果类型在 64 位机器上是大到可以容纳 stoul的,所以也不例外。unsigned long0xfffffffff


推荐阅读