我在这方面遇到了麻烦:
unsigned long value = stoul ( s, NULL, 11 );这给了我在c++ 98中的错误
error: 'stoul' was not declared in this scope它可以在C++11上工作,但我需要在C++98上使用这个。
发布于 2016-03-02 14:29:35
您可以使用来自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返回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;
}https://stackoverflow.com/questions/35749900
复制相似问题