一、简介
<sstream>类库定义了三种类:istringstream,ostringstream,stringstream.分别用来进行流的输入,流的输出,输入输出操作.在此演示stringstream的使用.**stringstream最大的特点是可以很方便的实现各种数据类型的转换,不需要像C语言中转换那么麻烦,而且转换非常安全.所以stringstream经常用于方便安全的类型转换.
二、用法
(1)数据的分割(string --> string)
#include<stdio.h>
#include<iostream>
#include<sstream>
using namespace std; string str[]; int main()
{
string line;
int cnt = ;
while (getline(cin, line)) //每次取一行
{
stringstream ss(line); //将字符串根据空格分隔成一个个单词
while (ss >> str[cnt])
{
cout << str[cnt++] << " ";
}
}
return ;
}
(2)数据的拼接
#include<stdio.h>
#include<iostream>
#include<sstream>
using namespace std; int main()
{
stringstream ss;
int num1 = ;
int num2 = ;
string str2 = "abc";
string str;
ss << num1;
ss << num2;
ss << str2;
ss >> str;
cout << str; //可以不同类型拼接,输出123456789abc return ;
}
(3)数据类型的转换
#include<stdio.h>
#include<iostream>
#include<sstream>
using namespace std; template<class T>
void Tostring(string &result, const T &t) //用模板将各种数值转化成string类型
{
stringstream ss;
ss << t;
ss >> result;
} int main()
{
stringstream ss;
string str;
string str2 = "1122334455a123";
int num1 = ;
float num2 = 3.1415926;
char arr[]; Tostring(str, num2);
cout << str << endl; ss.clear();
ss.str(""); //在另外一篇blog有解释
ss << num1;
ss >> str;
cout << str << endl; //int --> string,输出12345 ss.clear();
ss.str("");
ss << num2;
ss >> str;
cout << str << endl; //float --> string,输出3.14159,好像小数点5位之后的会丢掉 ss.clear();
ss.str("");
ss << str2;
ss >> num1; //string --> int,输出1122334455,遇到非数字会停止
cout << num1 << endl; ss.clear();
ss.str("");
ss << str2;
ss >> num2; //string --> float,输出1122334455,遇到非数字也会停止
cout << num1 << endl; ss.clear();
ss.str("");
ss << str2;
ss >> arr; //string --> char*,输出1 3,转换成其他类型数组不行
cout << arr[] <<" "<< arr[] << endl; return ;
}