std::stoul 的 C++98 替代品?

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);

一些差异:

  1. std::stoul的第二个参数是一个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
}
  1. 如果转换后的值超出 unsigned long 的范围,std::stoul 会抛出 out_of_range 异常,而 strtoul return ULONG_MAX并将 errno 设置为 ERANGE.

这是 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;
}