C++ Primer(第五版) 8.3.1节练习

本文探讨了C++中流操作的高级应用,包括如何处理文件读取过程中的错误,利用istringstream进行字符串解析,以及如何使用istringstream和vector来解析并存储人员信息。通过实例展示了如何读取和解析复杂的数据结构。

8.9 代码

#include <iostream>
#include <sstream>

using namespace std;

istream& in_out(istream &in)
{
	int temp;
	
	while (1) {
		cin >> temp;
		/* 到达文件结尾 */ 
		if (in.eof()) {
			cout << "EOF" << endl;
			break;
		}
		/* 系统级错误 */ 
		if (in.bad())
			throw runtime_error("iostream error!");
		/* 数据错误,清除错误标志,重新输入 */ 
		if (in.fail()) {
			cout << "format error, enter again: " << endl;
			in.clear();
			in.ignore(100, '\n');
			continue;	
		}
		cout << temp << endl;
	}
	
	return in;
}

int main(int argc, char *argv[])
{
	istringstream text("This is a test line.");
	
	in_out(text);
	
	return 0;
}

8.10 代码:

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

using namespace std;

int main(int argc, char *argv[])
{
	ifstream input(argv[1]);

	string line;
	vector<string> text;

	while(getline(input, line)) {
		text.push_back(line);
	}

	//输出验证
	string word;
	for (auto l : text) {
		istringstream strm(l);
		while(strm >> word)
			cout << word << endl;
	}

	return 0;

}

8.11 代码:定义在外层,使用str()成员, sstream strm; strm.str(s):将string s拷贝至strm中,注意重复使用字符串流时,每次都要clear().

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

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

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值