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
#include
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<

 

    2.使用stringstream。

#include
#include
#include    //字符串流头文件
using namespace std;
int main(void)
{
	string s;
	stringstream ss;
	int a=30;
	ss<>s;
	cout<

 

 

二,string型转int型

 

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

 

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

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

#include
#include
#include
using namespace std;
int main(void)
{
	string s="35";
	cout<

    2.使用stringstream。

#include
#include
#include
#include
using namespace std;
int main(void)
{
	string s="35";
	stringstream ss;
	int a;
	ss<>a;
	cout<

 

你可能感兴趣的:(C++学习)