首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++98替代性病::?

C++98替代性病::?
EN

Stack Overflow用户
提问于 2016-03-02 14:25:23
回答 1查看 2.8K关注 0票数 4

我在这方面遇到了麻烦:

代码语言:javascript
复制
unsigned long value = stoul ( s, NULL, 11 );

这给了我在c++ 98中的错误

代码语言:javascript
复制
error: 'stoul' was not declared in this scope

它可以在C++11上工作,但我需要在C++98上使用这个。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-02 14:29:35

您可以使用来自strtoulcstdlib

代码语言:javascript
复制
unsigned long value = strtoul (s.c_str(), NULL, 11);

一些差异:

  1. std::stoul的第二个参数是一个size_t *,它将被设置为转换数字之后的第一个字符的位置,而strtoul的第二个参数是char **类型,指向转换数字之后的第一个字符。
  2. 如果没有发生转换,std::stoul将抛出一个invalid_argument异常,而strtoul则不会(您必须检查第二个参数的值)。通常,如果您想检查错误:
代码语言:javascript
复制
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之间的区别。

代码语言:javascript
复制
#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;
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35749900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档