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

拜了个拜!

相关推荐
程序员-King.43 分钟前
【接口封装】——13、登录窗口的标题栏内容设置
c++·qt
萌の鱼1 小时前
leetcode 2826. 将三个组排序
数据结构·c++·算法·leetcode
Biomamba生信基地2 小时前
两天入门R语言,周末开讲
开发语言·r语言·生信
RAN_PAND2 小时前
STL介绍1:vector、pair、string、queue、map
开发语言·c++·算法
Bio Coder2 小时前
R语言安装生物信息数据库包
开发语言·数据库·r语言
Tiger Z2 小时前
R 语言科研绘图第 27 期 --- 密度图-分组
开发语言·程序人生·r语言·贴图
life_time_4 小时前
C语言(22)
c语言·开发语言
Minner-Scrapy4 小时前
DApp 开发入门指南
开发语言·python·web app
mit6.8245 小时前
[实现Rpc] 通信-Muduo库的实现 | && 完美转发 | reserve | unique_lock
c++·网络协议·rpc