[英]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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.