【C++类型转换】string 与 int 类型之间的转换以及string 与 char*、char[]转换

本文详细介绍了在C++中如何将字符串(string)与整数(int)相互转换的方法,包括使用stoi、strtol函数及stringstream对象实现string到int的转换,以及利用to_string方法和stringstream实现int到string的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、string 与 int

1. string 转换为 int:

解决方法之一:利用std::stoi()、stol()、stoll()函数 OR std::strtol()...

//(1)The Function Prototype
  //int  stoi(const std::string& str, std::size_t* pos = 0, int base = 10);

  //show an example of stoi function
  // Define an integer variable
  int i_temp = 100;
  string str_temp = "2019ewrabc";
  std::string::size_type size_type_temp = 3;
  int i_strToi = std::stoi(str_temp, &size_type_temp,16);

  cout << size_type_temp << endl;
  // the output is 5;
  //If pos is not a null pointer, then a pointer ptr - internal to the conversion functions - will
  //receive the address of the first unconverted character in str.c_str(),
  //and the index of that character will be calculated and stored in *pos, 
  //giving the number of characters that were processed by the conversion.
 
  cout << i_strToi << endl;
  //the output is 131486

  //(2)The Function Prototype
  //std::strtol(str.c_str(), &ptr, base)
  char* stop;
  int i_strtol = strtol(str_temp.c_str(), &stop,16);
  cout << i_strtol << endl;// output is 131486
  cout << stop << endl;// output is wrabc

  
  i_strtol = strtol(str_temp.c_str(), &stop,0);
  cout << i_strtol<<endl;// output is 2019
  cout << stop << endl;// output is ewrabc

解决方式之二:用sstream中定义的字符串流对象来实现

(图片来源于其他博客,侵权删)

int i_temp4 ;
  string str_temp="2000";
  stringstream stream2;
  stream2 << str_temp;
  stream2 >> i_temp4;
  cout << i_temp4 << endl<<typeid(i_temp4).name();
//output is 2000 int

2.int 转换为 string 

解决方法:利用to_string()方法

//int to string 
  int i_temp2 = 100;
  string str_temp2 = std::to_string(i_temp2);
  cout << str_temp2;

解决方法:用sstream中定义的字符串流对象来实现

 int i_temp3 = 100;
  string result;
  stringstream stream;
  stream << i_temp3;
  stream >> result;
  cout << result << endl<<typeid(result).name();

二、string 与 char、 char*

见博客:https://blog.youkuaiyun.com/steft/article/details/60126077

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值