首页 > 技术文章 > C++字符串转化为int类型的利器stoi函数详解

tsruixi 2020-05-23 21:14 原文

一、定义及参数介绍

  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

推荐阅读