C++字符串转化为int类型的利器stoi函数详解

一、定义及参数介绍

  1. int stoi (const string& str, size_t* idx = 0, int base = 10);
  2. int stoi (const wstring& str, size_t* idx = 0, int base = 10);
  3. 所属头文件为string.h
  4. 参数:
  • str:表示所要转化的字符串
  • idx:表示想要str中开始转化的位置,默认为从第一个字符开始。
  • base:表示要用的进制(如2进制、16进制,默认为10进制)转化为int类型十进制数字。

二、例子

// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}

OUT:
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3:  16579
-10010110001: -1201
0x7f: 127

原文链接: https://www.cnblogs.com/tsruixi/p/12944470.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++字符串转化为int类型的利器stoi函数详解

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/350294

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午6:15
下一篇 2023年3月2日 上午6:15

相关推荐