0

当从字符串提取数据到标量(char、short、int ...)时,我怎么能很容易地知道我想要获取的值是否超过了类型限制?

unsigned char          function(void)
{
    std::string        str = "259";
    std::ostringstream os(str);
    unsigned char      scalar; // could also be short, int, float or double

    if (str > /* limit of char */)
    {
        /* throw exception */
    }

    os >> scalar;
    return scalar;
}
4

1 回答 1

0

考虑新的C++11 转换函数,如std::stoi. std::out_of_range在这种情况下,他们应该抛出异常。不幸的是,这不会char直接处理这种情况,但您可以先转换为int,然后手动检查范围。

于 2014-02-27T17:30:50.323 回答