当前位置: 首页 > 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.mrgr.cn/news/36149.html

相关文章:

  • DBAPI如何实现插入数据前先判断数据是否存在,存在就更新,不存在就插入
  • 机器学习算法与Python实战 | 三万字详解!GPT-5:你需要知道的一切(上)建议收藏!
  • OpenCV4.8 开发实战系列专栏之 01- 环境搭建与图像读写
  • 使用 from __future__ import annotations 语句来允许在类型注释中使用尚未定义的类名
  • centos7安装Redis单机版
  • AI时代下的程序员:如何应对技术变革与提升竞争力
  • 先进封装技术 Part01---“凸块”(Bump)科普
  • 小孩真的需要手机上学吗?怎样远程了解他在学校用iPhone干什么?
  • 工作安排 - 华为OD统一考试(E卷)
  • Educational Codeforces Round 20 F. Coprime Subsequences(DP+容斥)
  • 深入解析网络通信关键要素:IP 协议、DNS 及相关技术
  • 股价上涨210%后,目标价又被花旗大幅上调,AppLovin还能继续上涨吗?
  • 前端文件上传全过程
  • PG逻辑订阅功能
  • 尚硅谷MyBatis笔记
  • Spring 的作用和优势
  • 省市区乡村五级地址库
  • C/C++语言基础--C++类数据、静态与非静态、常成员、友员、成员变量与函数指针等相关知识点
  • 3. 轴指令(omron 机器自动化控制器)——>MC_MoveZeroPosition
  • uboot — uboot命令的使用