字符串转int
我们可以使用atoi
函数来实现,但是参数需要传入字符指针,所以需要用到c_str()
函数,来获取字符串的字符指针,然后再作为参数传入。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string a = "123";
int res = atoi(a.c_str());
cout << res << endl;
return 0;
}
int转字符串
通过stringstream来进行转换。
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
int main()
{
stringstream ss;
int a = 54321;
string b;
ss << a;
ss >> b;
cout << b << endl;
return 0;
}