C++中字符串和int类型互相转换

字符串转int

我们可以使用atoi函数来实现,但是参数需要传入字符指针,所以需要用到c_str()函数,来获取字符串的字符指针,然后再作为参数传入。

#include 
#include 

using namespace std;

int main()
{
	string a = "123";
	int res = atoi(a.c_str());
	cout << res << endl;
	return 0;
}

int转字符串

通过stringstream来进行转换。

#include 
#include 
#include 

using namespace std;

int main()
{
	stringstream ss;
	int a = 54321;
	string b;
	ss << a;
	ss >> b;
	cout << b << endl;
	return 0;
}

你可能感兴趣的:(c++)