4.5

来源:互联网 发布:企业信息安全软件 编辑:程序博客网 时间:2024/05/17 06:52

/*
 *编写一个函数,其唯一的形参和返回值都是istream&类型。
 *该函数应一直读取流直到到达文件结束符为止
 *还应该将读到的内容输出到标准输出中,
 *最后,重设流使其有效,并返回流值。
 *以cin为实参来调用测试函数
 */
#include "get.hpp"
#include <iostream>
using namespace std;

int main()
{
 double dval;
 get(cin);
 cin >> dval;
 cout << dval << endl;
 return 0;
}


#ifndef GET
#define GET
#include <iostream>

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 << " ";
 }
 in.clear();
 return in;

}
#endif

 

 

 

 

 

 

 

 

 

 

/*
 *编写函数打开文件用于输入,、
 *将文件内容读入string类型的vector容器,
 *每一行存储为该容器对象的一个元素
 */

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
 ifstream ifcin;
 vector<string> ivec;
 string str;
 
 ifcin.open ("D:\\wer.txt"); //在D盘下新建wer.txt,并输入字符。

 if(!ifcin)
 {
  cerr << "open fail" << endl;
  return -1;
 }
 while( !ifcin.eof ())
 {
  getline(ifcin,str);
  ivec.push_back(str);
 }

 ifcin.close();

 for(vector<string>::iterator iter = ivec.begin();iter != ivec.end();++iter)
 {
  cout << *iter <<endl;
 }

 


 system("pause");
 return 0;
}