总结:
1、不能拷贝或对IO对象赋值
eg:
ofstream out1,out2;
out1=out2; //错误,不能对流对象赋值
ofstream print=(ofstream); //错误,不能初始化ofstream参数
out2=print(out2); //错误,不能拷贝流对象
2、条件状态
一旦一个流的操作失败,其上后序的IO操作都将失败,所以可以将流当做一个条件使用
eg:
int x,t=0;
while(cin>>x){
t++;
}
while循环表示检查表达式>>返回流的状态,如果操作成功,流保吃有效状态。
(操作失败的实例:数据类型不匹配,遇到EOF)
3、string流
头文件#include<sstream>中有istringstream(从string中读入数据),ostringstream(向string中写入数据)
stringstream(可以从string中读取,写入数据)
(1)istringstream
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
struct Per{
string name;
vector <string> ph;
};
int main(void)
{
string line,word;
vector <Per> person;
while(getline(cin,line)){
Per pp;
istringstream record(line); //将记录绑定到刚刚读入的行
record>>pp.name;
while(record>>word){ //全部读出后结束,适用于所有的>>(流输入)
pp.ph.push_back(word);
}
person.push_back(pp);
}
for(int i=0;i<person.size();i++){
cout<<person[i].name<<endl;
for(int j=0;j<person[i].ph.size();j++){
cout<<person[i].ph[j]<<" ";
}
cout<<endl;
}
return 0;
}
/*
zzz 123 456
sdfds 1242 43543534
erter 234 546545
*/
(2)stringstream特有操作
#include<iostream>
#include<sstream>
#include<vector>
#include<string>
using namespace std;
int main(void)
{
stringstream strm;
string str;
while(cin>>str){
strm.str(str); //将str拷贝到strm中 (会覆盖)
}
cout<<strm.str()<<endl; //返回strm中所保存的string的拷贝
return 0;
}
/*
1232
dsfs
s13423
*/