std::stoi 能否验证digit 的值是否超出base 范围?
Can std::stoi verify if the value of digit exceeds range of base?
我正在按以下方式使用 std::stoi
int ConvertToInt( const std::string& aVal )
{
int lVal = std::stoi( aVal, nullptr, 0 );
return lVal;
}
std::stoi 中的第三个参数被提供为 0 以自动转换 DEC 和 HEX 值。
我还使用 try-catch 结构来捕获 std::invalid_argument、std::out_of_range 和 ( ... ) 以为当我将数字提供为 0xgg 时不会抛出异常并且数字会转换为 0这不是我的本意。
是否可以捕获超出范围的数字并抛出一些异常?
std::stoi
解析字符串直到遇到无效字符,该字符被解释为整数结束。
Is it possbile to catch digits, which are out of range and throw some exception ?
是的。您可以使用 pos
参数。转换后,指向的整数将包含第一个未转换字符的索引。如果 *pos
不等于输入的大小,则有未转换的字符,这一定是无效的。在这种情况下你可以抛出异常。
我正在按以下方式使用 std::stoi
int ConvertToInt( const std::string& aVal )
{
int lVal = std::stoi( aVal, nullptr, 0 );
return lVal;
}
std::stoi 中的第三个参数被提供为 0 以自动转换 DEC 和 HEX 值。
我还使用 try-catch 结构来捕获 std::invalid_argument、std::out_of_range 和 ( ... ) 以为当我将数字提供为 0xgg 时不会抛出异常并且数字会转换为 0这不是我的本意。
是否可以捕获超出范围的数字并抛出一些异常?
std::stoi
解析字符串直到遇到无效字符,该字符被解释为整数结束。
Is it possbile to catch digits, which are out of range and throw some exception ?
是的。您可以使用 pos
参数。转换后,指向的整数将包含第一个未转换字符的索引。如果 *pos
不等于输入的大小,则有未转换的字符,这一定是无效的。在这种情况下你可以抛出异常。