8.3

题目:

编写一个函数,其唯一的形参和返回值都是 istream& 类型。该个函数应一直读取流直到到达文件结束符为止,还应将读到的内容输出到标准输出中。最后,重设流使其有效,并返回该流。

MyCode:

#include<iostream>
#include<limits>
#include<string>
using namespace std;

istream& f(istream& in)
{
	int ival;
	while(in >> ival, !in.eof())		//还是必须按两个结束符,才可以结束
	{
		if(in.bad())		//input stream is corrupted, bail out
			throw runtime_error("IO stream corrupted");
		if(in.fail())		//bad input (出现可恢复错误)
		{
			cerr << "bad data,  try again  " << endl;	//warn the user(提示用户)
			in.clear();		//reset the stream (恢复流)
			in.ignore(numeric_limits<streamsize>::max(), '\n');	//跳过类型非法的输入项,即刷新输入缓存区
			continue;		//继续读入数据
		}//读入正常
		cout << ival << "\t";
	}
	in.clear();
	return in;
}
int main()
{
	cout << "Enter some intengers(Ctr+Z \r Ctr+Z \r to end):" << endl;
	f(cin);
	string str;
	cout << "Enter a string:" << endl;
	cin >> str;
	cout << endl << str << endl;
	return 0;
}

你可能感兴趣的:(8.3)