C++ stoi 介绍

本文介绍了C++标准库中的std::stoi函数,用于将字符串转换为整数。函数接受一个字符串和基数作为参数,返回转换后的整数值,并更新索引指针到非数字字符的位置。示例代码展示了如何使用std::stoi进行不同基数的转换,包括十进制、十六进制和二进制,并输出转换结果。
摘要由CSDN通过智能技术生成

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 <iostream>   // std::cout
#include <string>     // 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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值