当前位置: 首页 > news >正文

【C++ Primer Plus习题】17.7

问题:

这里是引用
在这里插入图片描述

解答:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>using namespace std;const int LIMIT = 50;void ShowStr(const string& str);
void GetStrs(ifstream& fin, vector<string>& v);class Store
{
private:string str;ofstream* fout;
public:Store(ofstream&out):fout(&out){}bool operator()(const string& str);~Store(){}
};void ShowStr(const string& str)
{cout << str << endl;
}
void GetStrs(ifstream& fin, vector<string>& v)
{unsigned int len;char* p;while (fin.read((char*)&len, sizeof len)){p = new char[len];fin.read(p,len);v.push_back(p);}
}bool Store::operator()(const string& str)
{unsigned int len = str.length();if (fout->is_open()){fout->write((char*)&len, sizeof len);fout->write(str.data(), len);return true;}else{return false;}
}int main()
{vector<string> vostr;string temp;cout << "Enter strings (empty line to quit):\n";while (getline(cin, temp) && temp[0] != '\0')vostr.push_back(temp);cout << "Here is your input.\n";for_each(vostr.begin(), vostr.end(),ShowStr);ofstream fout("strings.txt", ios_base::in | ios_base::binary);for_each(vostr.begin(), vostr.end(), Store(fout));fout.close();vector<string>vistr;ifstream fin("strings.txt", ios_base::in | ios_base::binary);if (!fin.is_open()){cerr << "Could not open the file for input.\n";exit(EXIT_FAILURE);}GetStrs(fin, vistr);cout << "\nHere are the strings read from the file:\n";for_each(vistr.begin(), vistr.end(), ShowStr);return 0;
}

拜了个拜!

http://www.lryc.cn/news/446200.html

相关文章:

  • vue3(整合版)
  • 复制他人 CSDN 文章到自己的博客
  • 【算法——二分查找】
  • Cisco Packet Tracer的安装加汉化
  • MMain函数定义为WinMain函数看port1632.h和pwin32.h文件
  • 单词搜索问题(涉及递归等)
  • Redis的一些通用指令
  • C++中vector类的使用
  • cmaklist流程控制——调试及发布
  • 制作一个能对话能跳舞的otto机器人
  • git配置SSH
  • mozilla/pdf.js view.html加载指定页码
  • Qt之QFuture理解
  • 求二叉树的高度(递归和非递归)
  • Java查找算法——(四)分块查找(完整详解,附有代码+案例)
  • 进制数知识(2)—— 浮点数在内存中的存储 和 易混淆的二进制知识总结
  • 类似QQ聊天功能的Java程序
  • Redis 键值对数据库学习
  • 逆向推理+ChatGPT,让论文更具说服力
  • 「JavaScript深入」一文说明白JS的执行上下文与作用域
  • Qt C++设计模式->组合模式
  • Acwing Bellman-Ford SPFA
  • 我能禁止使用某协议的ip禁止访问我的资源吗
  • 快速理解TCP协议(二)——TCP协议中的拥塞控制机制详解
  • Linux:debug: systemtap: ubacktrace
  • 使用AI进行需求分析的案例研究
  • Python内置的re库
  • 毕业设计选题:基于ssm+vue+uniapp的面向企事业单位的项目申报小程序
  • jQuery 简介⑤属性操作
  • [Linux] Linux操作系统 进程的状态