加载中...
重温文件流和字符串流
第1节:“流”的基本概念与应用
第2节:C++和C标准输入输出同步
第3节:C++和C的格式化输入输出
第4节:重温文件流和字符串流
第5节:为自定义类型重载流操作
第6节:三大关联知识点综合强化复习
第7节:从零开始,实现日志流
课文封面

含两个视频。视频一讲解内存流(也就是字符串流)和文件流各自较为广泛的使用场景,视频二演练书中实践项目。(对应书本 10.1.4 小节)。

本课例程中,文件流使用了 ifstream 和 ofstream,而字符串流使用了 stringstream 。这么安排的原因是因为,这正是文件流和字符串流(也称为内存流)比较常见的用法。为什么?请看视频1。

视频一:理论讲解文件流与内存流的惯用法

视频二:上机实践

完整代码:

#include <iostream> #include <fstream> #include <sstream> //stringstream #include <list> #include <vector> using namespace std; template<typename Iter> void output(Iter const& beg, Iter const& end) { for (auto it = beg; it != end; ++it) { cout << *it << endl; } } void foo() { stringstream bufss; bool is_first = true; do { // 1、从控制台读入一个单词(不含空格) cout << "please input a word: "; string word; cin >> word; // 3、使用空格拼接每个单词,直到读入 "end" if (word == "end") { break; } if (!is_first) { bufss << ' '; // 使用空格拼接 } else { is_first = false; } // 2、把读到的单词输出到内存流 bufss << word; // bufss 作为 输出流 } while(true); // 4、将内存流中的内容,以字符串的形式,整体输出到屏幕 cout << "buffer :\n"; cout << bufss.str() << endl; // 5、从内存流中读出单词,偶数下标单词存入list,奇数下标单词存入vector list<string> lst; vector<string> vec; int count = 0; while(!bufss.eof()) // eof : 输入流,是否结束 { string word; bufss >> word; // 作为输入流 if (count % 2 == 0) { lst.push_back(word); } else { vec.push_back(word); } ++count; } // 6、将list和vector内的单词,输出到屏幕: cout << "list:\n"; output(lst.cbegin(), lst.cend()); cout << "vector:\n"; output(vec.cbegin(), vec.cend()); // 7、将list和vector中的单词交替输出到同一文件 string filename = "strings.txt"; ofstream ofs (filename); auto itLst = lst.cbegin(); auto itVec = vec.cbegin(); for (; itLst != lst.cend(); ++itLst, ++itVec) { ofs << *itLst << endl; if (itVec != vec.cend()) { ofs << *itVec << endl; } } ofs.close(); // 8、读出文件中的单词,再次显示到屏幕上 ifstream ifs(filename); if (!ifs) { cout << "file no found " << filename << endl; return; } cout << "read from file:\n"; while(!ifs.eof()) { string word; ifs >> word; cout << word << endl; } } int main() { foo(); }