C++ 98替代std :: stoul?

Jet*_*eph 4 c++ c++98

我在这里用这段代码遇到了麻烦:

unsigned long value = stoul ( s, NULL, 11 );
Run Code Online (Sandbox Code Playgroud)

这给了我c ++ 98的这个错误

error: 'stoul' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

它适用于C++ 11,但我需要在C++ 98上使用它.

Hol*_*olt 7

您可以使用strtoulcstdlib:

unsigned long value = strtoul (s.c_str(), NULL, 11);
Run Code Online (Sandbox Code Playgroud)

一些差异:

  1. 第二个参数std::stoul是a size_t *,它将被设置为转换后的数字后的第一个字符的位置,而第二个参数strtoul是类型,char **并指向转换后的数字后的第一个字符.
  2. 如果没有发生转换,则std::stoul抛出invalid_argument异常而不抛出异常strtoul(必须检查第二个参数的值).通常,如果要检查错误:
char *ptr;
unsigned long value = strtoul (s.c_str(), &ptr, 11);
if (s.c_str() == ptr) {
    // error
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果转换后的值超出了范围为unsigned long,std::stoul将引发out_of_range异常而strtoul返回ULONG_MAX,并设置errnoERANGE.

下面是定制的版本std::stoul应该表现得像标准之一,并总结之间的区别std::stoulstrtoul:

#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;
}
Run Code Online (Sandbox Code Playgroud)