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

拜了个拜!

相关推荐
Konata12几秒前
实现进阶的C/S通信
java·开发语言
Hill_HUIL1 分钟前
学习日志21-路由概述
学习
初听于你2 分钟前
Java 泛型详解
java·开发语言·windows·java-ee
rainbow68893 分钟前
Java17新特性深度解析
java·开发语言·python
bin91533 分钟前
C盘瘦身大作战:程序员的存储空间优化全攻略
c语言·开发语言·c盘清理·c盘清理技巧分享
hansang_IR3 分钟前
【记录】AT_abc400模拟赛
c++·算法·模拟赛
小秋学嵌入式-不读研版4 分钟前
智能台灯功能重设计方案
开发语言
Z.风止5 分钟前
Go-learning(1)
开发语言·笔记·后端·golang
阿昭L10 分钟前
C++异常处理机制反汇编(二):32位下基本类型异常分析
c++·逆向工程
知识分享小能手11 分钟前
Oracle 19c入门学习教程,从入门到精通,VC++ + Oracle 实现汽配管理系统(21)
c++·学习·oracle