【C++ Primer Plus习题】17.7

问题:


解答:

cpp 复制代码
#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;
}

拜了个拜!

相关推荐
xht083223 分钟前
PHP vs C语言:核心差异全解析
c语言·开发语言·php
yoothey23 分钟前
Java字节流与字符流核心笔记(问答+考点复盘)
java·开发语言·笔记
查古穆39 分钟前
python进阶-Pydantic模型
开发语言·python
沐知全栈开发41 分钟前
Bootstrap4 导航栏
开发语言
kyriewen1144 分钟前
异步编程:从“回调地狱”到“async/await”的救赎之路
开发语言·前端·javascript·chrome·typescript·ecmascript·html5
AI+程序员在路上1 小时前
嵌入式软件技术大全
linux·开发语言·arm开发·单片机
吴声子夜歌1 小时前
JavaScript——数据类型
开发语言·javascript·ecmascript
星空1 小时前
RAG学习第一节
学习
知识分享小能手1 小时前
MongoDB入门学习教程,从入门到精通,MongoDB入门指南 —— 知识点详解(2)
数据库·学习·mongodb
Jordannnnnnnn1 小时前
追赶33名
c++