C++ stoi 介绍

C++ stoi 介绍,第1张

C++ stoi 介绍 1、 功能

int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);

将str 的内容 解析为一个 特定base的int数值

2、参数 1. str

一个表示整数的string类型的对象

2. idx
  1. 如果为null,代表不使用这个参数
  2. 指向size_t类型对象的指针,该函数将其值设置为str中数值后面的下一个字符的位置,也就是str中既包含数字又包含非数字的话,那么该函数会将数值后面的第一个字符的位置赋值给这个指针。
3. base

确定以何种的基数去解释str中的数值。默认为10。如果填0的话,就按照str中的标志去判定(如0x)

3、例子
// stoi example
#include    // std::cout
#include      // std::string, std::stoi
using namespace std;
int main ()
{
  string dec = "2022, a new year";
  string hex = "403c";
  string bin = "-101010";
  string autoConvert = "0x6f";
  
  string::size_type sz;

  int i_dec = stoi(dec,&sz);
  int i_hex = stoi(hex,nullptr,16);
  int i_bin = stoi (bin,nullptr,2);
  int i_auto = stoi (autoConvert,nullptr,0);

  cout << dec << ": " << i_dec << "   n sz point to:" << dec[sz] << 'n';
  cout << hex << ": " << i_hex << 'n';
  cout << bin << ": " << i_bin << 'n';
  cout << autoConvert << ": " << i_auto << 'n';

  return 0;
}
输出:
2022, a new year: 2022   
sz point to:,
403c: 16444
-101010: -42
0x6f: 111
参考资料

https://www.cplusplus.com/reference/string/stoi/

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5691617.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存