C++primer(第五版)8.2.2节练习答案

练习8.9:使用你为8.1.2节(第281页)第一个练习所编写的函数打印一个istringstream对象的内容。


解答:


#include<iostream>
#include<sstream>

using std::istream;using std::string;using std::istringstream;using std::endl;using std::cout;

istream& func(istream& is)
{
	string buf;
	while(is>>buf)
		cout<<buf<<endl;

	is.clear();
	return is;	
}

int main()
{
	istringstream iss("hello");
	func(iss);

	return 0;
}


练习8.10:编写程序,将来自一个文件中的行保存在一个vector<string>中。然后使用一个istringstream从vector中读取数据元素,每次读取一个单词。


解答:

#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
#include<vector>

using std::cout;using std::endl;using std::string;using std::vector;using std::istringstream;

int main()
{
	vector<string> svec;
	std::ifstream ifs("sample.txt");
	if(!ifs)
	{
		std::cerr<<"No data?"<<endl;
		return -1;
	}

	string line;
	while(getline(ifs,line))
		svec.push_back(line);

	for(auto &s:svec)
	{
		istringstream iss(s);
		string word;
		while(iss>>word)
			cout<<word<<endl;
	}
	
	return 0;
}

练习8.11:本节的程序在外层while循环中定义了istringstream对象。如果record对象定义在循环外,你需要对程序进行怎样的修改?重写程序,将record的定义移到while循环外,验证你设想的修改方法是否正确。


解答:

#include<iostream>
#include<sstream>
#include<string>
#include<vector>

using std::cout;using std::cin;using std::string;using std::vector;using std::istringstream;

struct PersonInfo{
	string name;
	vector<string> phones;
};

int main()
{
	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 &p:people)
	{
		cout<<p.name<<" ";
		for(auto &s:p.phones)
			cout<<s<<" ";
		cout<<std::endl;
	}
	return 0;
}


练习8.12:我们为什么没有在PersonInfo中使用类内初始化?


解答:因为我们需要的是一个集合类,所以没有在PersonInfo中使用类内初始化。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值