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

拜了个拜!

相关推荐
xyliiiiiL5 分钟前
单例模式详解
java·开发语言·单例模式
Abaaba+8 分钟前
【编译、链接与构建详解】Makefile 与 CMakeLists 的作用
linux·开发语言·c++
清晨朝暮11 分钟前
【算法学习计划】贪心算法(中)
学习·算法·贪心算法
cainiao08060517 分钟前
Neuralink API开发指南:用Python读取脑电信号控制智能家居
开发语言·python·智能家居
独好紫罗兰22 分钟前
洛谷题单2-P2433 【深基1-2】小学数学 N 合一-python-流程图重构
开发语言·python·算法
闪电麦坤9523 分钟前
C#:常见 Console 类输入输出方法
开发语言·c#
独好紫罗兰23 分钟前
洛谷题单2-P5709 【深基2.习6】Apples Prologue 苹果和虫子-python-流程图重构
开发语言·python·算法
GalaxyPokemon27 分钟前
C/C++ 基础 - 回调函数
c语言·开发语言·c++
linwq834 分钟前
Kotlin基础知识学习(五)
学习·kotlin
安然无虞36 分钟前
31天Python入门——第18天:面向对象三大特性·封装继承多态
开发语言·后端·爬虫·python