失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > C++常用函数--stoi函数用法总结

C++常用函数--stoi函数用法总结

时间:2018-11-10 00:30:55

相关推荐

C++常用函数--stoi函数用法总结

stoi函数

作用是将 n 进制的字符串转化为十进制,使用时包含头文件string.

定义如下:

int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

参数:

str- 待转换的字符

pos- 其取值可以是一个空字符,在这种情况下,pos未被使用;另外如果pos不是空指针,函数将pos的值设置为str中数字后面的第一个字符的位置。

base- 字符中数字的进制,默认为10进制,如果base取值为0,则进制由字符串中的格式决定。

返回值:

如果转换成功的话,stoi函数将会把转换后的得到数字以int类型返回。

如果字符串中没有数字的话,将会抛出"invalid_argument"的异常

如果字符串中的数字转换后超过int的范围,将会抛出"out_of_range"的异常

因此使用stoi函数的时候最好加入异常处理。

例程如下:

#include <string>#include <iomanip>#include <utility>#include <iostream>#include <stdexcept>int main(){const auto data = {"45","+45"," -45","3.14159","31337 with words","words and 2","12345678901",};for (const std::string s : data){std::size_t pos{};try{std::cout << "std::stoi('" << s << "'): ";const int i {std::stoi(s, &pos)};std::cout << i << "; pos: " << pos << '\n';}catch(std::invalid_argument const& ex){std::cout << "std::invalid_argument::what(): " << ex.what() << '\n';}catch(std::out_of_range const& ex){std::cout << "std::out_of_range::what(): " << ex.what() << '\n';const long long ll {std::stoll(s, &pos)};std::cout << "std::stoll('" << s << "'): " << ll << "; pos: " << pos << '\n';}}std::cout << "\nCalling with different radixes:\n";for (const auto& [s, base]: {std::pair<const char*, int>{"11", 2}, {"22", 3}, {"33", 4}, {"77", 8},{"99", 10}, {"FF", 16}, {"jJ", 20}, {"Zz", 36}, }){const int i {std::stoi(s, nullptr, base)};std::cout << "std::stoi('" << s << "', " << base << "): " << i << '\n';}}

输出为:

std::stoi('45'): 45; pos: 2std::stoi('+45'): 45; pos: 3std::stoi(' -45'): -45; pos: 4std::stoi('3.14159'): 3; pos: 1std::stoi('31337 with words'): 31337; pos: 5std::stoi('words and 2'): std::invalid_argument::what(): stoistd::stoi('12345678901'): std::out_of_range::what(): stoistd::stoll('12345678901'): 12345678901; pos: 11Calling with different radixes:std::stoi('11', 2): 3std::stoi('22', 3): 8std::stoi('33', 4): 15std::stoi('77', 8): 63std::stoi('99', 10): 99std::stoi('FF', 16): 255std::stoi('jJ', 20): 399std::stoi('Zz', 36): 1295

参考资料

std::stoi

如果觉得《C++常用函数--stoi函数用法总结》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。