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

拜了个拜!

相关推荐
像名字一样难取的昵称几秒前
Linux学习笔记:十八、Linux文件的压缩,解压缩一站式学习
linux·运维·笔记·学习·ubuntu·ssh
缺点内向4 分钟前
如何在 C# 中将 Word 文档转换为 EMF(增强型图元文件)
开发语言·c#·word·.net
老华带你飞7 分钟前
学生宿舍管理|基于java + vue学生宿舍管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
雍凉明月夜7 分钟前
深度学习网络笔记Ⅰ(CNN)
网络·笔记·深度学习·神经网络·学习·cnn
Filotimo_14 分钟前
在java后端开发中,redis的用处
java·开发语言·redis
superman超哥31 分钟前
仓颉Option类型的空安全处理深度解析
c语言·开发语言·c++·python·仓颉
MyBFuture34 分钟前
C# 哈希表与堆栈队列实战指南
开发语言·windows·c#·visual studio
网安_秋刀鱼34 分钟前
【java安全】java安全基础
java·开发语言·安全·web安全
你好音视频42 分钟前
FFmpeg FLV解码器原理深度解析
c++·ffmpeg·音视频
Data_agent43 分钟前
OOPBUY模式淘宝1688代购系统搭建指南
开发语言·爬虫·python