《C++ Primer》(5th)习题解答——8.9(学习使用istringstream对象)

题目描述

在这里插入图片描述

代码

#include <iostream>
#include <stdexcept>
#include <sstream>
#include <string>

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

istream &func(istream &);

int main()
{
	string s("a b c");
	istringstream in(s); //将string类型变量s的值复制至in对象中
	func(in); //istringstream继承自iostream,因此,尽管func的形参类型为istream &,仍可向其传递istringstream类型的in对象
	return 0;
}

istream &func(istream &in)
{
	string v;
	while (in >> v)
	{
		if (in.bad())
			throw std::runtime_error("IO流错误");
		if (in.fail())
		{
			std::cerr << "数据错误,请重试: " << endl;
			in.clear();
			in.ignore(100, '\0');
			continue;
		}
		cout << v << endl;
	}
	in.clear();
	return in;
}

输出:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值