2016-03-02 135 views
3

我无法在这里使用此代码:C++ 98替代std :: stoul?

unsigned long value = stoul (s, NULL, 11); 

,让我这个错误使用C++ 98

error: 'stoul' was not declared in this scope 

它适用于C++ 11,但我需要这对C++ 98。

+2

为什么地球上你传递( )''stoul',如果's'的类型是'std :: string',它接受'std :: string'? – MikeCAT

+1

你可以试试'strtoul'。 – i486

+0

@MikeCAT我很抱歉,现在编辑它 –

回答

6

可以使用strtoulcstdlib

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 
} 
  • 如果转换值超出范围为unsigned longstd::stoul抛出一个out_of_range异常而strtoul返回并且将errno设置为ERANGE

  • 这里是定制版本的std::stoul应该表现得像标准之一,并总结std::stoulstrtoul之间的区别是:'s.c_str

    #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; 
    } 
    
    +0

    感谢您的工作! 8分钟后再检查一下! –