3
我无法在这里使用此代码:C++ 98替代std :: stoul?
unsigned long value = stoul (s, NULL, 11);
,让我这个错误使用C++ 98
error: 'stoul' was not declared in this scope
它适用于C++ 11,但我需要这对C++ 98。
我无法在这里使用此代码:C++ 98替代std :: stoul?
unsigned long value = stoul (s, NULL, 11);
,让我这个错误使用C++ 98
error: 'stoul' was not declared in this scope
它适用于C++ 11,但我需要这对C++ 98。
可以使用strtoul
从cstdlib
:
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
返回并且将errno
设置为ERANGE
。这里是定制版本的std::stoul
应该表现得像标准之一,并总结std::stoul
和strtoul
之间的区别是:'s.c_str
#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;
}
感谢您的工作! 8分钟后再检查一下! –
为什么地球上你传递( )''stoul',如果's'的类型是'std :: string',它接受'std :: string'? – MikeCAT
你可以试试'strtoul'。 – i486
@MikeCAT我很抱歉,现在编辑它 –