C++中将int转变成string和string转变成int

时间:2022-12-07 10:30:53

int to string

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s;
    char c[100];
    int m=199;
    itoa(m,c,10);
    s=c;
    s.insert(0,"zhang");
    cout<<s<<endl;
    return 0;


}

string to int

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s="56sd";
    int a=atoi(s.c_str());
    cout<<a<<endl;
    return 0;
}

 

 

另外一种方法,包含#include<sstream>,例如

#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
	stringstream s;
	string ss="234";
	s<<ss;
	s<<"abcd";


	string s0;
	int n;
	s>>n;
	s>>s0;

	cout<<n<<"  "<<s0<<endl;

	return 0;
}