c++prime习题第八章

 

 1.

#include 
#include 
using namespace std;

istream& f(istream &in){
	int v;
	while(in >> v , !in.eof()){
		if(in.bad()){	//打开文件时发生错误 如文件受损或硬件故障
			throw runtime_error("IO流错误"); 
		}
		if(in.fail()) {  //方法用于判断最后一次读取数据的时候是
		//否遇到了类型不配的情况,若是返回true(如果遇到了EOF,该方法也返回true) 
			cerr << "数据错误,请重试:" << endl; 		//输出错误信息 
			in.clear();
			in.ignore(100,'\n');
			continue;
		}
		cout << v <

 2.

#include 
#include 
#include 
#include 

using namespace std;

int main(){
	ifstream in("data.txt");
	if(!in){
		cerr << "无法打开输入文件" << endl;
		return -1; 
	}
	
	string line;
	vector words;
	while(getline(in,line)){
		words.push_back(line);
	}
	
	in.close();		//输入完毕,关闭文件
	
	vector::const_iterator it = words.begin();
	while(it != words.end()){
		cout << *it << endl;
		++it;
	} 
	
	return 0;
}

 

3.

#include 
#include 
#include 
#include 

using namespace std;

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

int main(){
	ostringstream msg;
	msg << "C++ primer 第五版" << endl;
	istringstream in(msg.str());
	f(in);
	return 0; 
}

你可能感兴趣的:(c++,开发语言)