C++中int型与string型互相转化的几种方式

以vs2010为例。

一,int型转string型

    1.使用to_string()函数

    函数原型:①string to_string (long long val);

                    ②string to_string (unsigned long long val);

                    ③string to_string (long double val);

#include<iostream>
#include<string>
using namespace std;
int main(void)
{
	string s;
	int a=30;
	s=to_string(a);   //这种会报错vs2010没有int型参数,必须强制转换long long
	s=to_string(long long(a));
        cout<<s<<endl;
    return 0;
}//输出:30

    2.使用stringstream。

#include<iostream>
#include<string>
#include<sstream>    //字符串流头文件
using namespace std;
int main(void)
{
	string s;
	stringstream ss;
	int a=30;
	ss<<a;
	ss>>s;
	cout<<s<<endl;
    cout<< os.str() << endl; //或者利用字符串流的str函数获取流中的内容
    return 0;

二,string型转int型

    1.stoi()函数(stoi/stol/stoll等等函数

    函数原型:int stoi(     const string& _Str,      size_t *_Idx = 0,     int _Base = 10 );

    stoi(字符串,起始位置,2~32进制),将n进制的字符串转化为十进制。

#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
	string s="35";
	cout<<stoi(s,0,10);    //这里的10指的是输入的进制
    return 0;
}

//输出:35

    2.使用stringstream。

#include<cstdio>
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(void)
{
	string s="35";
	stringstream ss;
	int a;
	ss<<s;
	ss>>a;
	cout<<a<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/vir_lee/article/details/80650621