繁体   English   中英

C ++ 98替代std :: stoul?

[英]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 longstd::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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM