c++ - 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(并且不会引发异常)。为什么会这样?
解决方案
让我们看看在 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 long
0xfffffffff
推荐阅读
- apache - 在 Amazon Linux 实例上使用 docker-compose 安装 Apache OpenWhisk 卡在“等待 Whisk 调用程序启动...”
- css - 将 WooCommerce 产品图像缩小到移动视图中?
- javascript - 如何使用 this.props 将值传递给 onclick 回调
- codenameone - 代号一 SpanLabel 文本不占全角
- r - 从 Lat Lon 数据创建距离海岸 (km) 变量?
- sql - SQL 根据其他表值创建标识列
- spring-mvc - Spring REST 自定义反序列化
- java - 使用原始类型为反射子类动态应用类型参数
- python - 如何在 Python 中获取当前活动键盘布局的内容?
- python - 由于 EnvironmentError 无法安装软件包:[Errno 2]