#include<sstream>
stringstream 对象用于输入一行字符串,以 空格 为分隔符把该行分隔开来
string str= "hello world I am very happy!";
stringstream sstream(str); //sstream<<
while (sstream)
{
string substr;
sstream>>substr;
cout << substr << endl; //也可vec.push_back(substr);
}
/*****************************************************类型转换******************************************************/
1.类型转换
1.1利用stringstream进行常见类型转换
(int、long、float、double、long double、long long)
/--------------------int转string------------------/
stringstream stream;
string result;
int i = 1000;
stream << i; //将int输入流
stream >> result; //从stream中抽取前面插入的int值
cout << result << endl; // cout the string "1000"
/--------------------int转char *------------------/
stringstream stream;
char result[8] ;
stream << 8888; //向stream中插入8888
stream >> result; //抽取stream中的值到result
cout << result <<endl; // 屏幕显示 "8888"
1.2利用to_string() 进行常见类型转换, 返回值为string
s1=to_string(10.5); //double到string
s2=to_string(123); //int到string
s3=to_string(true); //bool到string
1.3定义一个通用的转换模板,用于任意类型之间的转换
template<class out_type,class in_value>
out_type convert(const in_value & t)
{
stringstream stream;
stream<<t;//向流中传值
out_type result;//这里存储转换结果
stream>>result;//向result中写入值
return result;
}
int main()
{
double d;
string salary;
string s="12.56";
d=convert<double>(s);//d等于12.56
salary=convert<string>(9000.0);//salary等于”9000”
return 0;
}
/*********************************************
stringstream补充************************************************/
2.stringstream补充
2.1重复利用stringstream对象
如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;
在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。
stringstream stream;
int first, second;
stream<< "456"; //插入字符串
stream >> first; //转换成int
cout << first << endl;
stream.clear(); //在进行多次转换前,必须清除stream,否则第二个数据可能输出乱码
stream << true; //插入bool值
stream >> second; //提取出int
cout << second << endl;
2.2选择性 读取stingstream 对象中的数据
string test = "-123 9.87 welcome to, 989, test!";
stringstream strm(test);
int i;
float f;
char c;
char buff[1024];
strm >> i;
cout <<"读取int类型:"<< i << endl;
strm >> f;
cout <<"读取float类型:"<<f << endl;
strm >> c;
cout <<"读取char类型:"<< c << endl;
strm >> buff;
cout <<"读取buffer类型:"<< buff << endl;
//1.如果遇到一个字符值等于第二个参数,那么就停止ignore()
strm.ignore(100, ','); //2.如果ignore100个字符之后还没遇到值等于第二参数的字符,也得停止ignore()
//因此100是ignore()所能忽略的最大字符数。此时忽略了“to,”
strm >> buff;
cout <<"读取buffer类型:"<< buff << endl;
strm >> i;
cout <<"第二次 读取int类型:"<< i << endl;
strm >> i;
cout <<"第二次 读取int类型:"<< i << endl;
strm >> f;
cout <<"第二次 读取float类型:"<<f << endl;
strm >> c;
cout <<"第二次 读取char类型:"<< c << endl;