1. 程式人生 > >C++Primer Plus筆記——第十七章 輸入、輸出和檔案課後程式設計練習答案

C++Primer Plus筆記——第十七章 輸入、輸出和檔案課後程式設計練習答案

課後程式設計練習答案

習題1              習題2             習題3            習題4              習題5            習題6

習題1

#include<iostream>
int main()
{
	using namespace std;
	cout << "Enter a text,report the number(end with $):\n";
	int count=0;
	char r;
	while (cin.peek()!='$')		
	{
			cin.get(r);				
		if (r != '$')
		{
			cout << r;
			count++;
		}
	}
	char next;
	cin >> next;
	cout << "\nThe number of character is: " << count << endl;
	cout << "And the next character is: " << next << endl;
	return 0;
}

習題2

#include<iostream>
#include<fstream>
#include<string>
int main(int argc,char *argv[])
{
	using namespace std;
	if (argc != 2)
	{
		cerr << "Usage: " << argv[0] << " filename[s]\n";
		exit(EXIT_FAILURE);
	}
	ofstream fin;
	fin.open(argv[1]);			
	if (!fin.is_open())			
	{
		cerr << "Could not open " << argv[0] << "\n";
		exit(EXIT_FAILURE);
	}
 
	cout << "Give me something you want add to the file(<CTRL>+<Z>+<ENTER> to end): ";
	string  ch;
	while (cin.fail()==false)	
	{
		getline(cin, ch);
		cout << ch;
		fin << ch;
	}
	cout << "Input complete!\n";
	fin.close();
	return 0;
}

習題3

#include<iostream>
#include<fstream>
int main(int argc, char *argv[])
{
	using namespace std;
	if (argc != 3)
	{
		cerr << "Usage: " << argv[0] << " resource filename[s] target[s]\n";
		exit(EXIT_FAILURE);
	}
	ofstream fin;
	fin.open(argv[2]);			
	if (!fin.is_open())
	{
		cerr << "Could not open " << argv[0] << "\n";
		exit(EXIT_FAILURE);
	}
	ifstream fou;
	fou.open(argv[1]);
	if (!fou.is_open())
	{
		cerr << "Could not open " << argv[0] << "\n";
		exit(EXIT_FAILURE);
	}
	char c;
	while (fou.get(c))
	{
		cout << c;
		fin.put(c);		
	}
	cout << "\nCopy complete!\n";	
	fou.close();
	fin.close();
	return 0;
}

習題4

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
int main()
{
	using namespace std;
	ofstream fin;
	cout << "This program is connect two file content to another file.\n";
	cout << "Enter the frist filename: ";
	string filename;
	getline(cin, filename);
	fin.open(filename.c_str());
	cout << "Now,give me something to the frist resource file:\n";
	string file;
	while (cin.fail() == false)	
	{
		getline(cin, file);
		fin<<file << endl;
	}
	fin.close();
	cin.clear();
	cout << "Enter the second filename: ";
	string filename2;
	getline(cin, filename2);
	fin.open(filename2.c_str());
	cout << "Now,give me someing to the second resource file:\n";
	while (cin.fail() == false)
	{
		getline(cin, file);
		fin<<file << endl;
	}
	fin.close();
	cin.clear();
	cout << "Enter the target filename: ";
	string target;
	getline(cin, target);
	fin.open(target.c_str());
	ifstream fou,fou2;
	fou.open(filename);
	fou2.open(filename2);
	if (!fou.is_open()||!fou2.is_open())
		{
			cerr << "Could not open the source!"<<filename<<endl<<filename2<< "\n";
			exit(EXIT_FAILURE);
		}
	string file2;
	while (!fou.eof()&&!fou2.eof())
	{
		getline(fou, file);
		getline(fou2, file2);
		fin << file + ' ' + file2 << endl;
		cout<< file + ' ' + file2 << endl;
	}
	while (!fou.eof())
	{
		getline(fou, file);
		fin << file << endl;
		cout << file << endl;
	}
	while (!fou2.eof())
	{
		getline(fou2, file);
		fin << file << endl;
		cout << file << endl;
	}
	fou.close();
	fou2.close();
	fin.close();
	return 0;
}

習題5

#include<iostream>
#include<fstream>
#include<string>
#include<set>
#include<algorithm>
#include<iterator>				
int main()
{
	using namespace std;
	ostream_iterator<string, char>out(cout, "\n");			
	ifstream fin;
	char filename[10];
	set<string>fresource;
	char temp[10];
	string file;
	cout << "Enter the Mat friends filename: ";
	cin.getline(filename, 10);
	fin.open(filename);
	if (!fin.is_open())
	{
		cerr << "Cant open the file " << filename << endl;
		exit(EXIT_FAILURE);
	}
	while (!fin.eof())
	{
		fin.getline(temp,10);
		fresource.insert(temp);		
		cout << temp<<endl;
	}
	fin.close();
	cout << "Enter the Pat friends filename: ";
	cin.getline(filename, 10);
	fin.open(filename);
	if (!fin.is_open())
	{
		cerr << "Cant open the file " << filename << endl;
		exit(EXIT_FAILURE);
	}
	set<string>fresource2;		
	while (!fin.eof())
	{
		fin.getline(temp, 10);
		fresource2.insert(temp);
		cout << temp << endl;
	}
	fin.close();
	cout << "Enter the Target filename: ";
	cin.getline(filename, 10);
	ofstream fou;
	fou.open(filename);
	set<string>target;					
	set_union(fresource.begin(), fresource.end(), fresource2.begin(), fresource2.end(),
		insert_iterator<set<string>>(target, target.begin()));
	cout << "Friends they have:\n";
	copy(target.begin(), target.end(), out);
	ostream_iterator<string, char>fileout(fou, "\n");	
	copy(target.begin(), target.end(), fileout);
	fou.close();
	return 0;
}

習題6

//fileemp.h
#ifndef FILEEMP_H
#define FILEEMP_H
#include<iostream>
#include<string>
#include<fstream>
using std::string;
using namespace std;
enum classkin { Employee, Manager, Fink, Highfink };
class abstr_emp
{
private:
	string fname;
	string lname;
	string job;
public:
	abstr_emp() :fname("No name"), lname("no name "), job("no job") {};
	abstr_emp(const string&fn, const string&ln, const string &j) :fname(fn)
		, lname(ln), job(j) {};
	virtual void ShowAll()const;
	virtual void SetAll();
	virtual void writeall(ofstream &fo);		
	virtual void getall(ifstream &fi);		
	friend std::ostream&operator<<(std::ostream &os, const abstr_emp&e);
	virtual ~abstr_emp() = 0 {};
};
class employee :public abstr_emp
{
public:
	employee(const string &fn, const string&ln, const string&j) :abstr_emp(fn, ln, j) {};
	employee() :abstr_emp() {};
	virtual void ShowAll()const { abstr_emp::ShowAll(); };
	virtual void SetAll() { abstr_emp::SetAll(); };
	void writeall(std::ofstream &fo);	
	 void getall(std::ifstream &fi);		
};
class manager :virtual public abstr_emp
{
public:
	manager() :abstr_emp(), inchargeof(0) {};
	manager(const string &fn, const string &ln,
		const string &j, int ico = 0) :abstr_emp(fn, ln, j), inchargeof(ico) {};
	manager(const abstr_emp&e, int ico) :abstr_emp(e), inchargeof(ico) {};
	manager(const manager&m);
	virtual void ShowAll()const;
	virtual void SetAll();
	 void writeall(std::ofstream &fo);		
	 void getall(std::ifstream &fi);			
protected:
	int InChargeOf()const { return inchargeof; }	//outut method
	int &InChargeOf() { return inchargeof; }		//input method
	void FileChangeOf(std::ofstream &fou)const { fou << inchargeof << "\t"; }
	void FileChangeOf(std::ifstream&fin) { fin >> inchargeof; }
private:
	int inchargeof;
};
 
class fink :virtual public abstr_emp
{
private:
	string reportsto;
protected:
	const string ReportsTo()const { return reportsto; }
	string &ReportsTo() { return reportsto; }
	void FileReportsTo(std::ofstream &fou) {fou << reportsto;}
	void FileReportsTo(std::ifstream&fin) { fin >> reportsto; }
public:
	fink() :abstr_emp(), reportsto("null") {};
	fink(const string &fn, const string &ln,
		const string &j, const string &rpo) :abstr_emp(fn, ln, j), reportsto(rpo) {};
	fink(const abstr_emp&e, const string &rpo) :abstr_emp(e), reportsto(rpo) {};
	fink(const fink&e);
	virtual void ShowAll()const;
	virtual void SetAll();
	 void writeall(std::ofstream &fo);		
	 void getall(std::ifstream &fi);		
};
class highfink :public manager, public fink
{
public:
	highfink() {};				
	highfink(const string &fn, const string &ln,
		const string &j, const string &rpo, int ico)
		:abstr_emp(fn, ln, j), fink(fn, ln, j, rpo), manager(fn, ln, j, ico) {};
	highfink(const abstr_emp&e, const string &rpo, int ico)
		:abstr_emp(e), fink(e, rpo), manager(e, ico) {};
	highfink(const fink &f, int ico)
		:abstr_emp(f), fink(f), manager(f, ico) {};
	highfink(const manager &m, const string &rpo)
		:abstr_emp(m), manager(m), fink(m, rpo) {};
	highfink(const highfink&h)
		:abstr_emp(h), manager(h), fink(h) {};
	virtual void ShowAll()const;
	virtual void SetAll();
	 void writeall(std::ofstream &fo);	
	void getall(std::ifstream &fi);			
};
#endif // !EMP_H
#include"fileemp.h"
 
using std::cout;
using std::endl;
using std::cin;
//abstr_emp methods
 
void abstr_emp::ShowAll()const
{
	cout <<"\t\t"<< lname << "," << fname << "\t"
		<< job;
}
void abstr_emp::SetAll()
{
	cout << "Enter frist name: ";
	std::getline(cin, fname);
	cout << "Enter last name: ";
	std::getline(cin, lname);
	cout << "Job: ";
	std::getline(cin, job);
}
void abstr_emp::writeall(ofstream &fo)
{
	fo<<lname <<endl<< fname <<endl<<job<<endl;
}
void abstr_emp::getall(ifstream &fi)		
{
	std::getline(fi, lname);
	std::getline(fi, fname);
	std::getline(fi, job);
}
//only display name
std::ostream&operator<<(std::ostream &os, const abstr_emp&e)
{
	os << "Name: " << e.lname << " , " << e.fname;
	return os;
}

void employee::writeall(std::ofstream &fo)
{
	fo << Employee;
	abstr_emp::writeall(fo);
}
void employee::getall(std::ifstream &fi)
{
	abstr_emp::getall(fi);
}
//manage methods
manager::manager(const manager&m) :abstr_emp(m)	//copy construction function
{
	inchargeof = m.inchargeof;
}
 
void manager::ShowAll()const
{
	cout << endl;
	abstr_emp::ShowAll();
	cout <<"\t"<< inchargeof;
}
void manager::SetAll()
{
	abstr_emp::SetAll();
	cout << "Enter the inchangeof count: ";
	cin >> inchargeof;
	while (cin.get() != '\n')
		continue;
}
void manager::writeall(std::ofstream &fou)
{
	fou << Manager;
	abstr_emp::writeall(fou);
	fou << inchargeof<<endl;
}
void manager::getall(std::ifstream &fin)
{
	abstr_emp::getall(fin);
	fin >> inchargeof;
}
//fink methods
fink::fink(const fink&e) :abstr_emp(e)
{
	reportsto = e.reportsto;
}
 
void fink::ShowAll()const
{
	cout << endl;
	abstr_emp::ShowAll();
	cout << "\t" << reportsto;
}
 
void fink::SetAll()
{
	cout << "Enter the reportsto: ";
	std::getline(cin, reportsto);
	while (cin.get() != '\n')
		continue;
}
void fink::writeall(std::ofstream &fou)
{
	fou << Fink;
	abstr_emp::writeall(fou);
	fou << reportsto<<endl;
}
void fink::getall(std::ifstream &fin)
{
	abstr_emp::getall(fin);
	std::getline(fin,reportsto);
}
//highlink methods
void highfink::ShowAll()const
{
	cout << endl;
	abstr_emp::ShowAll();	
	cout<<"\t"<< manager::InChargeOf();
	cout<<"\t" << fink::ReportsTo()<<endl;
}
void highfink::SetAll()
{
	abstr_emp::SetAll();
	string temp;				
	int tem;
	cout << "Enter the inchangeof count: ";
	cin >> tem;
	cin.get();		
	cout << "Enter the reportsto: ";
	std::getline(cin, temp);
	ReportsTo() = temp;
	InChargeOf() = tem;
}
void highfink::writeall(std::ofstream &fou)
{
	fou << Highfink;
	abstr_emp::writeall(fou);
	manager::FileChangeOf(fou);
	fink::FileReportsTo(fou);
}
void highfink::getall(std::ifstream &fin)
{
	abstr_emp::getall(fin);
	manager::FileChangeOf(fin);
	fink::FileReportsTo(fin);
}
#include<iostream>
using namespace std;
#include"fileemp.h"
const int MAX = 10;
void showClassType();
int main(void)
{
	abstr_emp *pc[MAX];				
	cout << "This program show the file of class Empoyee,input the data name to continue.\n";
	cout << "Enter the target file:";
	char filename[MAX];
	cin.getline(filename, MAX);
	ifstream fin;
	fin.open(filename);
	if (!fin.is_open())
	{
		cerr << "Sorry ,can't open " << filename << endl;
		exit(EXIT_FAILURE);
	}
	char ch;
	int i = 0;
	int classtype;
	while (fin >> classtype)
	{
		switch (classtype)
		{
		case Employee:pc[i] = new employee; break;
		case Manager:pc[i] = new manager; break;
		case Fink:pc[i] = new fink; break;
		case Highfink:pc[i] = new highfink; break;
		}
		pc[i]->getall(fin);
		pc[i]->ShowAll();
		i++;
	}
	fin.close();
	ofstream fou;
	fou.open(filename, ios_base::out | ios_base::app);
	int idex=0;
	showClassType();
	while (cin >> ch&&ch != 'q'&&idex < MAX)
	{
		cin.get();
		switch (ch)
		{
		case 'a':pc[idex]= new employee;
			pc[idex]->SetAll();
			break;
		case 'b':pc[idex] = new manager;
			pc[idex]->SetAll(); break;
		case 'c':pc[idex] = new fink;
			pc[idex]->SetAll(); break;
		case 'd':pc[idex] = new highfink;
			pc[idex]->SetAll(); break;
		default:cout << "Error type!\n"; break;
		}
		idex++;
		showClassType();
	}
	for (i = 0; i < idex; i++)
		pc[i]->writeall(fou);
	fou.close();
	fin.clear();
	fin.open(filename);
	cout << "Here is the redice file:\n";
	while ((fin >> classtype).get(ch))
	{
		switch (classtype)
		{
		case Employee:pc[i] = new employee; break;
		case Manager:pc[i] = new manager; break;
		case Fink:pc[i] = new fink; break;
		case Highfink:pc[i] = new highfink; break;
		}
		pc[i]->getall(fin);
		pc[i]->ShowAll();
		i++;
	}
	fin.close();
	cout << "Bye!\n";
	return 0;
}
void showClassType()
{
	cout << "What class type do you want to creat:\n "
		"a)Employee  b)Manage  c)Fink  d)Highfink  q)quit\n";
}

 習題7

#include<iostream>
#include<fstream>
#include<algorithm>
#include<string>
#include<vector>
#include<iterator>
void ShowStr(const std::string&s) { std::cout << s << std::endl; }
void GetStrs(std::ifstream&fi, std::vector<std::string>&s);
class Store
{
private:
	std::ofstream&fou;
public:
	Store(std::ofstream&os) :fou(os) {};
	void operator()(const std::string&s)
	{
		size_t len = s.size();			
		fou.write((char*)&len, sizeof(std::size_t));	
		fou.write(s.data(), len);

	}
};
int main()
{
	using namespace std;
	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("string.dat", ios_base::out | ios_base::binary);
	for_each(vostr.begin(), vostr.end(), Store(fout));
	fout.close();
	vector<string>vistr;
	ifstream fin("string.dat", ios_base::in | ios_base::binary);
	if (!fin.is_open())
		{
		cerr << "Could not open file for input.\n";
		exit(EXIT_FAILURE);
		}
	GetStrs(fin, vistr);
	cout << "\nHere are the strings read from the file:\n";
	for_each(vostr.begin(), vostr.end(), ShowStr);
	return 0;
}
void GetStrs(std::ifstream&fi, std::vector<std::string>&ve)
{
	size_t len;		
	while (fi.read((char *)&len, sizeof(size_t)))
	{	
		char *st = new char[len];
		fi.read(st, len);
		st[len + 1] = '\0';
		ve.push_back(st);
	}
 
}