c++ primer 8.1.2节练习(关于流的知识)

8.1

#include <iostream>  
#include <string>

using namespace std;

istream & Process(istream & i)//对于流对象,不能拷贝和赋值,必须使用引用来传递实参
{
	int test;
	while (i >> test||!i.eof())
	{
		if (i.bad())
			throw runtime_error("IO流发生不可恢复的错误");
		if (i.fail())
		{
			cout << "输入数据类型错误,请重试" << endl;
			//此时别忘记要重新复位
			i.clear();
			i.ignore(2, '\n');//会跳过错误字符的后2个字符(包括错误字符),或者遇到'\n'结束
			continue;
		}
		cout << test<<endl;
	}

	i.clear();//对标志位复位
	return i;
}

int main()
{
	if (Process(cin).good())
		cout << "已经将cin复位" << endl;
	system("pause");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章