《C++ Primer》5th 課後練習 第八章 IO庫 11-14

練習8.11 本節的程序在外層while循環中定義了istringstream 對象。如果record 對象定義在循環之外,你需要對程序進行怎樣的修改?重寫程序,將record的定義移到while 循環之外,驗證你設想的修改方法是否正確。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct PersonInfo
{
	string name;
	vector<string> phones;
};
int main(int argc, char **argv)
{
	string line, word;
	vector<PersonInfo> people;
	istringstream record;
	while (getline(cin, line)) {
		PersonInfo info;
		record.clear();
		record.str(line);
		record >> info.name;
		while (record >> word)
			info.phones.push_back(word);
		people.push_back(info);
		
	}
	for (auto item : people) {
		cout << item.name << ends;
		for (auto num : item.phones) {
			cout << num << ends;
		}
		cout << endl;
	}
	return 0;
}

練習8.12 我們爲什麼沒有在PersonInfo中使用類內初始化?

因爲此處我們使用聚合類即可,不需要類內初始值。

練習8.13 重寫本節的電話號碼程序,從一個命名文件而非cin讀取數據。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct PersonInfo
{
	string name;
	vector<string> phones;
};
int main(int argc, char **argv)
{
	string line, word;
	vector<PersonInfo> people;
	string file("123.txt");
	ifstream fin(file);

	istringstream record;
	while (getline(fin, line)) {
		PersonInfo info;
		record.clear();
		record.str(line);
		record >> info.name;
		while (record >> word)
			info.phones.push_back(word);
		people.push_back(info);
		
	}
	for (auto item : people) {
		cout << item.name << ends;
		for (auto num : item.phones) {
			cout << num << ends;
		}
		cout << endl;
	}
	system("pause");
	return 0;
}
/*
mogan 123 321
drew 222
ddd 555 666 777
*/

練習8.14 我們爲什麼將entrynums定義爲 const auto&

遍歷字符串容器時,用引用可以節省拷貝時間和空間。

定義爲const,保證在使用過程中不會更改其值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章