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

拜了个拜!

相关推荐
lightqjx几秒前
【C++】list 常见使用和模拟实现
开发语言·c++
无聊的小坏坏10 分钟前
从零开始:C++ 多进程 TCP 服务器实战(续篇)
服务器·c++·tcp/ip
ceclar12315 分钟前
C++容器queue
开发语言·c++
陈皮话梅糖@25 分钟前
Speckit和Claude 的初体验
开发语言·ide
屈冠成28 分钟前
C语言数组:编辑世界的坚固桥梁
c语言·开发语言·算法
启诚科技35 分钟前
树上二分(树的重心)
c++·算法·二分·树的重心
读书读傻了哟1 小时前
Windows 10 下 VS Code 配置 C++ 开发环境(MinGW)
c++·windows·mingw
zzzyyy5381 小时前
STL简介
开发语言·c++
zyq99101_11 小时前
树与二叉树的奥秘全解析
c语言·数据结构·学习·1024程序员节
微露清风1 小时前
系统性学习C++-第七讲-string类
java·c++·学习