【c++ primer读书笔记】【第8章】IO流
1、iostream定义了读写流的基本类型,fstream定义了读写命名文件的类型,sstream定义了读写string对象的类型。
|
头文件 |
类型 |
|
iostream |
istream, wistream从流读取数据 ostream, wostream向流写入数据 iostream, wiostream读写流 |
|
fstream |
ifstream, wifstream从文件读取数据 ofstream, wofstream向文件写入数据 fstream, wfstream读写文件 |
|
sstream |
istringstream, wistringstream从string读取数据 ostringstream, wostringstream向string写入数据 stringstream, wstringstream读写string |
2、IO对象不能拷贝或赋值,不能将形参或返回类型设置为流类型;读写IO对象会改变其状态,因此传递和返回的IO对象的引用不能是const的。
3、IO类定义了一些函数和标志,可以用来访问和操作流的条件状态。
4、刷新输出缓冲区
cout << "hi" << endl; //输出hi和一个换行,然后刷新缓冲 cout << "hi" << flush; //输出hi,然后刷新缓冲,不添加数据 cout << "hi" << ends; //输出hi 和一个空字符,然后刷新缓冲
unitbuf操纵符:告诉流在接下来的每次写操作之后都进行一次flush操作
cout<<unitbuf; //所有输出操作后都会立即刷新缓冲区 cout<<nounitbuf; //回到正常的缓冲方式
5、string流
istringstream从string读取数据,ostringstream向string写入数据,stringstream既可以从string读取数据也可以向string写入数据
将一个data.txt文件中的行保存在一个vector<string>中,然后用istringstream从vector读取数据元素,每次读取一个整数并求和。data.txt里的数据如下:
1 2 3 4 5 6 7 8 9 10完整程序如下:
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include<fstream>
using namespace std;
int main(){
string line;
vector<string> vec;
int sum=0;
ifstream file("data.txt");
while(getline(file,line))
vec.push_back(line);
for(auto& l:vec){
istringstream is(l);
int word;
while(is>>word)
sum+=word;
}
cout<<sum<<endl;
system("pause");
return 0;
}
程序运行结果:
posted on 2015-03-24 16:21 ruan875417 阅读(214) 评论(0) 收藏 举报
浙公网安备 33010602011771号