cppPrimer学习8th

8.1#

8.2#

Copy
/* 编写函数,接受一个istream &参数,返回值也是istream&。此函数必须从给定流中读取数据,直至遇到文件结束标识符时停止。 它将读取的数据打印在标准输出上。完成这些操作后,在返回流之前,对流进行复位,使其处于有效状态。 */ #include <iostream> using namespace std; istream &readeof(istream &in) { string s; while (in >> s && !in.eof()) { cout << s; in.clear(); } in.clear(); } int main(int argc, char const *argv[]) { readeof(cin); cout << "Get EOF" << endl; while (1) ; return 0; }

8.3#

Copy
while (cin >> i) /* ... */ // 遇到结束符 // 如果i是int 但是输入了其他字符

8.4#

8.5#

Copy
/* 8.4 编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个独立的元素存于vector中 8.5 按照单词分割 */ #include <string> #include <vector> #include <iostream> #include <fstream> using namespace std; void Each(istream &in, string option) { if (!in) { cerr << "Check FIle" << endl; while (1) ; } string s; vector<string> v; if (option == "line") { while (getline(in, s)) v.push_back(s); } else { while (in >> s) v.push_back(s); } for (auto a : v) { cout << a << endl; } } int main(int argc, char const *argv[]) { string filepath = "C:\\JLink.log"; ifstream in(filepath); cout << "Split By Line" << endl; Each(in, "line"); in.close(); cout << "Split By Word" << endl; in.open(filepath); Each(in, "word"); while (1) ; return 0; }

8.9#

Copy
/*使用8.1.2节第一个练习所编写的函数打印一个istringstream对象的内容*/ /* 编写函数,接受一个istream &参数,返回值也是istream&。此函数必须从给定流中读取数据,直至遇到文件结束标识符时停止。 它将读取的数据打印在标准输出上。完成这些操作后,在返回流之前,对流进行复位,使其处于有效状态。 */ #include <iostream> #include <sstream> using namespace std; istream &readeof(istream &in) { string s; while (in >> s) { cout << s; in.clear(); } cout << endl; in.clear(); } int main(int argc, char const *argv[]) { //readeof(cin); stringstream ss("1234567"); readeof(ss); cout << "Get EOF" << endl; while (1) ; return 0; }

8.10#

Copy
/* 8.10 编写程序,将来自一个文件中的行保存在一个vector中,然后使用一个istringstream从vector读取数据元素,每次读取一个单词。 */ #include <sstream> #include <string> #include <vector> #include <iostream> #include <fstream> using namespace std; int main(int argc, char const *argv[]) { string filepath = "C:\\JLink.log"; ifstream in(filepath); if (!in) { cout << "Check File" << endl; } vector<string> line; string s; while (getline(in, s)) { line.push_back(s); } for (auto c : line) { stringstream ss(c); string ch; while (ss >> ch) { cout << ch << endl; } } while (1) ; return 0; }

8.11#

Copy
/* 8.11 本节的程序在外层while循环中定义了istringstream对象。 如果record对象定义在循环之外,你需要对程序做怎样的修改? 重写程序,将record的定义移到while循环之外,验证你设想的修改方法是否正确。 */ //使用string的clear

8.12#

Copy
我们为什么没有在PersonInfo中使用类内初始化? 因为这里我们使用了聚合类,不需要类内初始化

8.14#

Copy
我们为什么要将entry和nums定义为const auto&。 使用引用避免拷贝 使用const 因为不会赋值
posted @   zongzi10010  阅读(158)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示
CONTENTS