问题描述:
编写一个函数,其唯一的形参和返回值都是 iftream& 类型。该个函数应一直读取流直到到达文件结束符为止,还应将读到的内容输出到标准输出中。最后,重设流使其有效,并返回该流。
My Code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
ifstream get(ifstream &file)
{
string str;
while(!file.eof())
{
getline(file, str);
cout << str << endl;
}
file.close();
file.clear();
return file;
}
int main()
{
ifstream file;
string filename;
cout << "Input the name of file:" << endl;
cin >> filename;
file.open(filename.c_str());
if(!file) //error:warn the user; bail out!
{
cerr << "error: can not open file: " << filename << endl;
return -1;
}
get(file);
return 0;
}
Reference Code:
由于ifstream继承了istream,因此可将ifstream对象传递形参为isteram引用的函数。
//习题8.3中定义的get.h
std::istream& get (std::istream& in)
{
int ival;
while(in >> ival, !in.eof())
{
if(in.bad()) //系统级错误,不可恢复
throw std::runtime_error("IO stream corrupted");
if(in.fail()) ///出现可恢复错误
{
std::cerr << "bad data, try again "; //提示用户
in.clear(); //回复流
in.ignore(200, ' '); //跳过类型非法的输入项
continue; //继续读入数据
}//读入正常
std::cout << ival << " ";
}
}
#include "get.h"
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string fileName;
cout << "Enter file name: " << endl;
cin >> fileName;
ifstream inFile(fileName.c_str());
if(!inFile)
{
cerr << "error: can not open input file: " << fileName << endl;
return -1;
}
get(inFile);
return 0;
}
——桑海整理