【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;
}

拜了个拜!

相关推荐
Thomas_YXQ4 小时前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
aini_lovee4 小时前
C# 快递单打印系统(万能套打系统)
开发语言·c#
MZZ骏马4 小时前
C++ 极简模式的日志
c++
天启HTTP4 小时前
开启全局代理后网络变慢,问题出在哪
开发语言·前端·网络·tcp/ip·php
丑过三八线4 小时前
Runc 深度解析:从原理到实操
java·linux·开发语言·docker·容器·rpc
STDD4 小时前
ntfy 自托管推送通知服务搭建:一条 curl 命令向手机发送通知
java·开发语言·智能手机
小林ixn4 小时前
从拼多多手机号验证到模板引擎:深入正则表达式与 JS 字符串处理
开发语言·javascript·正则表达式
AbandonForce4 小时前
滑动窗口:定长滑动窗口与不定长滑动窗口
数据结构·c++·算法
xian_wwq4 小时前
【学习笔记】「大模型安全:攻击面演化史」第 02 篇-越狱攻防战
笔记·学习