[英]C++98 alternative to std::stoul?
I'm having trouble here with this code: 我在这里用这段代码遇到了麻烦:
unsigned long value = stoul ( s, NULL, 11 );
that gives me this error with c++ 98 这给了我c ++ 98的这个错误
error: 'stoul' was not declared in this scope
It works on C++11, but I need this on C++98. 它适用于C ++ 11,但我需要在C ++ 98上使用它。
You can use strtoul
from cstdlib
: 你可以使用
cstdlib
strtoul
:
unsigned long value = strtoul (s.c_str(), NULL, 11);
Some differences: 一些差异:
std::stoul
is a size_t *
which will be set to the position of the first character after the converted number, while the second argument of strtoul
is of type char **
and points to the first character after the converted number. std::stoul
的第二个参数是size_t *
,它将被设置为转换后的数字后第一个字符的位置,而strtoul
的第二个参数是char **
类型,并指向转换后的数字后的第一个字符。 std::stoul
throw a invalid_argument
exception while strtoul
does not (you must check the value of the second argument). std::stoul
抛出invalid_argument
异常,而strtoul
则不会(你必须检查第二个参数的值)。 Typically, if you want to check for error: char *ptr;
unsigned long value = strtoul (s.c_str(), &ptr, 11);
if (s.c_str() == ptr) {
// error
}
unsigned long
, std::stoul
throws a out_of_range
exception while strtoul
return ULONG_MAX
and set errno
to ERANGE
. unsigned long
, std::stoul
抛出一个out_of_range
而例外strtoul
返回ULONG_MAX
并设置errno
到ERANGE
。 Here is custom version of std::stoul
that should behave like the standard one and summarizes the difference between std::stoul
and strtoul
: 这是
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.