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

拜了个拜!

相关推荐
陈年老古董3 分钟前
PyTorch食物图像分类实战:从数据集制作到CNN模型训练全流程详解
pytorch·深度学习·学习·机器学习·分类·cnn
明志数科7 分钟前
从300克Ego头环看第一人称数据采集趋势:设备轻量化之后,场景端壁垒在哪
数码相机·学习
持敬chijing19 分钟前
Python-数据类型-列表
开发语言·python·青少年编程
有点。29 分钟前
*C++哈夫曼树与哈夫曼编码
java·c++·servlet
笨鸟先飞的橘猫36 分钟前
系统设计第十七天决策卡
学习·游戏
啦啦啦啦啦zzzz37 分钟前
利用RAII机制进行日志的采集
linux·服务器·c++·网络编程·c++20
Sunshing151 小时前
Lyapunov方程系统本身稳定性判定与镇定性判定
笔记·学习
nLif1 小时前
基于GTK的简易MFC对话框兼容层 -- MfcToGTK
linux·c++·mfc·gtk
写后端的胖头鱼1 小时前
【高频面试题】Java 基础类型 + 包装类 + String 互相转换
java·开发语言
matlab代码2 小时前
基于matlab自助水果超市水果识别收费系统(GUI界面)【源码67期】
开发语言·matlab