Dav*_*one 92 c++ string std c++11
C++ 11添加了一些新的字符串转换函数:
http://en.cppreference.com/w/cpp/string/basic_string/stoul
它包括stoi(string to int),stol(string to long),stoll(string to long long),stoul(string to unsigned long),stoull(string to unsigned long long).值得注意的是它是一个stou(字符串到无符号)函数.有什么理由不需要它,但所有其他的都是吗?
Ker*_* SB 28
最轻松的答案是C库没有相应的" strtou",而C++ 11字符串函数都只是围绕C库函数的薄弱包装:std::sto*函数镜像strto*和std::to_string函数使用sprintf.
编辑:作为KennyTM指出,无论是stoi和stol使用strtol作为底层的转换功能,但它仍然是神秘的,为什么而存在stoul使用strtoul,也没有相应的stou.
Mik*_*our 21
我不知道为什么stoi存在但不是stou,但是stoul假设之间的唯一区别stou是检查结果是否在以下范围内unsigned:
unsigned stou(std::string const & str, size_t * idx = 0, int base = 10) {
unsigned long result = std::stoul(str, idx, base);
if (result > std::numeric_limits<unsigned>::max()) {
throw std::out_of_range("stou");
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
(同样,stoi也类似于stol,只是使用不同的范围检查;但由于它已经存在,因此无需担心具体如何实现它.)