题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/72db70c5720eefb0c12e9fad827eeff6.png)
代码
#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;
}
输出:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ab1f43d2de274339d61a9ee333f02aed.png)