我在这里用这段代码遇到了麻烦:
unsigned long value = stoul ( s, NULL, 11 );
Run Code Online (Sandbox Code Playgroud)
这给了我c ++ 98的这个错误
error: 'stoul' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
它适用于C++ 11,但我需要在C++ 98上使用它.
您可以使用strtoul从cstdlib:
unsigned long value = strtoul (s.c_str(), NULL, 11);
Run Code Online (Sandbox Code Playgroud)
一些差异:
std::stoul是a size_t *,它将被设置为转换后的数字后的第一个字符的位置,而第二个参数strtoul是类型,char **并指向转换后的数字后的第一个字符.std::stoul抛出invalid_argument异常而不抛出异常strtoul(必须检查第二个参数的值).通常,如果要检查错误:char *ptr;
unsigned long value = strtoul (s.c_str(), &ptr, 11);
if (s.c_str() == ptr) {
// error
}
Run Code Online (Sandbox Code Playgroud)
unsigned long,std::stoul将引发out_of_range异常而strtoul返回ULONG_MAX,并设置errno到ERANGE.下面是定制的版本std::stoul应该表现得像标准之一,并总结之间的区别std::stoul和strtoul:
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1566 次 |
| 最近记录: |