标签:style blog os io 使用 strong ar 数据 div
一 int转string
第一种方法:
#include <iostream>
#include <string>
using namespace std;
int main()
{
	int n = 65535;
	char t[256];
	string s;
	sprintf(t, "%d", n);
    s = t;
	cout << s << endl;
	return 0;
}
第二种方法:
#include <iostream>
#include <string>
#include <strstream>
using namespace std;
int main()
{
	int n = 65535;
	strstream ss;
	string s;
    ss << n;
	ss >> s;
	cout << s << endl;
	return 0;
}
第三种方法:
//char *itoa( int value, char *string,int radix);
 // 原型说明:
 // value:欲转换的数据。
 // string:目标字符串的地址。
 // radix:转换后的进制数,可以是10进制、16进制等。
 // 返回指向string这个字符串的指针
 int aa = 30;
 char c[8];
 itoa(aa,c,16);
 cout<<c<<endl; // 1e
第四种方法:
使用boost库中的lexical_cast
int aa = 30; string s = boost::lexical_cast<string>(aa); cout<<s<<endl; // 30
二  string转化为int
1、使用strtol(string to long) 
1 string s = "17";
2  char* end;
3  int i = static_cast<int>(strtol(s.c_str(),&end,16));
4  cout<<i<<endl; // 23
5 
6  i = static_cast<int>(strtol(s.c_str(),&end,10));
7  cout<<i<<endl; // 17
2、使用sscanf
1 int i;
2  sscanf("17","%D",&i);
3  cout<<i<<endl; // 17
4 
5  sscanf("17","%X",&i);
6  cout<<i<<endl; // 23
7 
8  sscanf("0X17","%X",&i);
9  cout<<i<<endl; // 23
3、使用stringstream
1  string s = "17";
2 
3  stringstream ss;
4  ss<<s;
5 
6  int i;
7  ss>>i;
8  cout<<i<<endl; // 17
注:stringstream可以吞下任何类型,根据实际需要吐出不同的类型。
4、使用boost库中的lexical_cast
1  string s = "17";
2  int i = boost::lexical_cast<int>(s);
3  cout<<i<<endl; // 17
标签:style blog os io 使用 strong ar 数据 div
原文地址:http://www.cnblogs.com/qxzy/p/3951686.html