C++ ofstream as function parameter

Description

C++ ofstream as function parameter

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int getOpen(ofstream&);
void inOut(ofstream&);
int main()// w ww .  ja  v a 2s  . c  o  m
{
   ofstream outFile;
   getOpen(outFile);    // open the file
   inOut(outFile);      // write to it
   return 0;
}
int getOpen(ofstream& fileOut)
{
   string name;
   cout << "\nEnter a file name: ";
   getline(cin,name);
   fileOut.open(name.c_str());   // open the file
   if (fileOut.fail())   // check for successful open
   {
      cout << "Cannot open the file" << endl;
      exit(1);
   }
   else
      return 1;
}
void inOut(ofstream& fileOut)
{
      const int NUMLINES = 5;  // number of lines
      int count;
      string line;
      cout << "Please enter five lines of text:" << endl;
      for (count = 0; count < NUMLINES; ++count)
      {
         getline(cin,line);
         fileOut << line << endl;
      }
      cout << "\nThe file has been successfully written.";
      return;
}



PreviousNext

Related