C++98 alternative to std::stoul?
C++98 alternative to std::stoul?
我在这段代码上遇到了问题:
unsigned long value = stoul ( s, NULL, 11 );
这给了我这个错误与C ++ 98
error: 'stoul' was not declared in this scope
它适用于 C++11,但我在 C++98 上需要它。
您可以使用cstdlib
中的strtoul
:
unsigned long value = strtoul (s.c_str(), NULL, 11);
一些区别:
std::stoul
的第二个参数是一个size_t *
,它将设置为转换后数字后第一个字符的位置,而strtoul
的第二个参数的类型为char **
,指向转换后的数字后的第一个字符。- 如果未发生转换,
std::stoul
引发invalid_argument
异常,而strtoul
没有(必须检查第二个参数的值)。通常,如果要检查错误:
char *ptr;
unsigned long value = strtoul (s.c_str(), &ptr, 11);
if (s.c_str() == ptr) {
// error
}
- 如果转换后的值超出
unsigned long
的范围,std::stoul
抛出out_of_range
异常,同时strtoul
返回ULONG_MAX
并将errno
设置为ERANGE
。
以下是std::stoul
的自定义版本,其行为应与标准版本类似,并总结了std::stoul
和strtoul
之间的区别:
#include <string>
#include <stdexcept>
#include <cstdlib>
#include <climits>
#include <cerrno>
unsigned long my_stoul (std::string const& str, size_t *idx = 0, int base = 10) {
char *endp;
unsigned long value = strtoul(str.c_str(), &endp, base);
if (endp == str.c_str()) {
throw std::invalid_argument("my_stoul");
}
if (value == ULONG_MAX && errno == ERANGE) {
throw std::out_of_range("my_stoul");
}
if (idx) {
*idx = endp - str.c_str();
}
return value;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- std::stoul not throwing std::out_of_range
- Std::stoul在C++失败后没有被抓住
- std::stoul 在带有 NDK r13b 的 Android 版 Qt 应用程序上出错
- C++98 alternative to std::stoul?
- 如何在Android中使用std::stoul和std::stoul