1、IO类——总体介绍
1、IO对象无拷贝或赋值函数
2、条件状态
将流当作条件使用的代码就等价于!fail(),而eof和bad操作只能表示特定的错误。
3、管理条件状态
可以通过存储iostate来保存cin状态,当cin在其他函数使用完之后恢复。
4、管理输出缓冲
以下三种方式可以强制刷新输出缓冲
可通过cin.tie(&ostream)自行指定关联输出流。
2、文件输入输出
使用文件流对象
通过ifstream或者ofstream可以进行文件的输入输出,值得注意的是,如果使用<<进行文件输出,即使指定了用二进制输出,也会将int型等数据转化为字符串输出,如下
int _tmain(int argc, _TCHAR* argv[])
{
int a;
ofstream outf;
outf.open("二进制.dat", ofstream::binary);
a = 123;
outf << a << endl;
return 0;
}
结果如下
3、string流
istringstream从string读取数据,ostringstream向string写入数据,stringstream可以读写
示例
ifstream inf;
string temp;
string name;
string singlephone;
vector<string> phonenum;
inf.open("文本.txt", ofstream::binary);
if (inf)
{
while (getline(inf, temp))
{
istringstream file(temp);
file >> name;
cout << name << "\t";
while (file >> singlephone)
{
phonenum.push_back(singlephone);
cout << singlephone << "\t";
}
cout << endl;
}
}
输出与输出
stringstream就像一个string容器一样,输入的是string,输出也是string,好处是可以按照读文本的方式读取,自动忽略空格与回车。
心得体会
感觉这一张讲来将去都是在讲读写文本,而二进制读取则没有怎么讲,例如write(&ofstream,size);
好处是对读写文本有了更深的体会。