参考:http://blog.csdn.net/xw20084898/article/details/21939811
http://nnssll.blog.51cto.com/902724/198237/
http://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html
一、stringstream通常是用来做数据转换的。
1、例如int转string:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::stringstream stream;
std::string result;
int i = 1000;
stream << i; //将int输入流
stream >> result; //从stream中抽取前面插入的int值
std::cout << result << std::endl; // print the string "1000"
}
2、char*:
int main()
{
std::stringstream stream;
char result[8] ;
stream << 8888; //向stream中插入8888
stream >> result; //抽取stream中的值到result
std::cout << result << std::endl; // 屏幕显示 "8888"
}
3、再进行多次转换的时候,必须调用stringstream的成员函数clear();
#include <sstream>
#include <iostream>
int main()
{
std::stringstream stream;
int first, second;
stream<< "456"; //插入字符串
stream >> first; //转换成int
std::cout << first << std::endl;
stream.clear(); //在进行多次转换前,必须清除stream
stream << true; //插入bool值
stream >> second; //提取出int
std::cout << second << std::endl;
}
————————————————————————————————————
二、sprintf函数
char str[10];
int a=1234321;
sprintf(str,"%d",a);
--------------------
char str[10];
double a=123.321;
sprintf(str,"%.3lf",a);
--------------------
char str[10];
int a=175;
sprintf(str,"%x",a);//10进制转换成16进制,如果输出大写的字母是sprintf(str,"%X",a)
三、to_string (int val);
int num=1;
string str=to_string(num);