《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,保证在使用过程中不会更改其值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值