sstream
头文件定义的三个类型来支持IO操作。
- istringstream :从string中读取数据
- ostringstream :向string中写入数据
- stringstream:即可以从string 中读取数据,也可以向其中写入数据。
sstream
的一些特有操作
// ssm01是一个未绑定的stringstream对象
stringstream ssm01;
// ssm02是一个stringstream对象,保存字符串 s 的一个拷贝
stringstream ssm02(s);
// 返回ssm02所保存的string字符串的拷贝
ssm02.str();
// 将字符串 s 拷贝到ssm01中,返回void
ssm01.str(s);
一、istringstream
读取string流
1、>>
方式读取
该方法将字符串中的数据读取,忽略所有空格。
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string str01 = { " hello this @ just a test! @ # && thanks " };
istringstream ism(str01);
string tmp;
while (ism>>tmp)
{
cout << tmp << endl;
}
system("pause");
return 0;
}
2、getline()
方式读取
该方式会将所有空格读取,其默认的分隔符是换行符号\n
,可以自行设定分隔符
(1)、默认换行符为分割符
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string str01 = { " hello this @ just a test! @ # && thanks \nu some one is here" };
istringstream ism(str01);
string tmp;
while (getline(ism,tmp))
{
cout << tmp << endl;
}
system("pause");
return 0;
}
(2)、当自行设定分割符为@
时,它会按照此字符来进行分割,但是当遇到换行符\n
时,也会作为分割依据。
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string str01 = { " hello this @ just a test! @ # && thanks \nu some one is here" };
istringstream ism(str01);
string tmp;
while (getline(ism,tmp,'@'))
{
cout << tmp << endl;
}
system("pause");
return 0;
}
二、ostringstream
向string流写入数据
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string str01 = "hello,,here,is";
string str02 = "thanks for this! ";
// 创建ostringstream对象时绑定到指定字符串
ostringstream osm01(str01);
// 创建空对象,然后再输出到该对象
ostringstream osm02;
osm02 << str02;
string res01 = osm01.str(); //将osm01中所保存的string字符串赋给str02
string res02 = osm02.str();
cout << "res01= " << res01 << endl;
cout << "str02= " << res02 << endl;
system("pause");
return 0;
}
三、stringstream
向string中读写数据
1、用于不同数据类型间的转换
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
stringstream ssm;
int num, num01 = 10;
string str, str01 = "666";
//将变量num1从int 类型转换成 string 类型
ssm << num01; //向string流写入数据
ssm >> str; // 向string流读取数据
cout << "str= " << str << endl;
ssm.clear();//清除流中的数据
// 将变量str01从string 类型转换成int类型
ssm << str01;
ssm >> num;
cout << "num= " << num << endl;
system("pause");
return 0;
}
2、用于多string流集中输出
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
stringstream ssm;
ssm << "hello " << "this is";
ssm << " some";
ssm << " @1234";
cout << ssm.str() << endl;
system("pause");
return 0;
}