C++98 alternative to std::stoul?

C++98 alternative to std::stoul?

本文关键字:stoul std alternative to C++98      更新时间:2023-10-16

我在这段代码上遇到了问题:

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返回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;
}