C++ int和string类型互转实用方法汇总

C++ int和string类型互转实用方法汇总,第1张

目录

1、int 转 string

2、string 转 int

方法1.

方法2.


1、int 转 string

使用到头文件#include中的stringstream,

#include 
#include 
 using namespace std;
int main()
{
  int i = 45634535;
  stringstream ss;
  ss << i;//int值传给stringstream
  string out_string = ss.str();//stringstream转string类型
  cout << out_string << "\n";
  return 0;
}

注意的是:stringstream类型变量,不能自动释放内存,多次用到时,最好要配合.clear(); 主动释放内存。

2、string 转 int 方法1.

通过stringstream作为中间体,实现string转int


#include 
#include 
using namespace std;
int main()
{ 

	int x;
	string str = "-10";
	string str1 = "10";
	stringstream ss;
	ss << str;//string转stringstream
	ss >> x;//stringstream转int
	cout << x << endl;
	ss.clear();    //多次使用stringstream时,这段程序不能省略!
	ss << str1;
	ss >> x;
	cout << x << endl;
	return 0;
}

 Tips:由于stringstream不会主动释放内存,在多次使用stringstream时,会造成不必要的内存浪费,可使用ss.str(""),清空其占用的内存

方法2.

用到C语言中的方法atoi(字符串首地址),其头文件为#include ,它的功能是将字符串转成int类型,注意的是,它的参数类型要求为字符串首地址,所以对于string类型,不能直接把变量放进去,而是要用到string方法c_str()f返回其首字符地址

#include 
#include 
using namespace std;

int main()
{ 
	int x;
	string str = "-10";
	string str1 = "-10agdgd";
	string str2 = "da10";
	x = atoi(str.c_str());//返回首地址
	cout << x << endl;
	x = atoi(str1.c_str());		 //atoi()函数遇到字母时会自动停下
	cout << x << endl;
	x = atoi(str2.c_str());    //atoi()函数转,字符串首字母不为数字时,输出为0 
	cout << x << endl;
}

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

原文地址: https://outofmemory.cn/langs/674934.html

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

发表评论

登录后才能评论

评论列表(0条)

保存