// copyWhileBreak.cpp
//
// Copies one text file to a new file.
// The input text file name is entered by the user.
// The name of copy will be the name of the original file,
// prefixed by "copy-".
//
// Illustrates  how to read a file line by line,
// using a while loop with a break statement.

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

using namespace std;

int main()
{
   // Announce purpose of program:
   cout << "This program copies a text file, fixing "
                     << "end-of-line markers." << endl;
   cout << "The copy's filename will be prefixed by \"copy-\"."
                     << endl;

   // Obtain filename from user input, as a string class object:
   cout << "Enter filename:> ";
   string filename;
   getline(cin, filename);

   // Prepare to read from file:
   ifstream inputFile;             // file input stream
   inputFile.open(filename.c_str());

   // Check whether input file was opened successfully:
   if ( !inputFile )
   {
      cout << "Cannot read file " << filename << "." << endl;
      return 1;
   }  // if

   // Generate output filename:
   filename.insert(0, "copy-");    // output filename

   // Prepare to write to output file:
   ofstream outputFile;            // file output stream
   outputFile.open(filename.c_str());

   // Check whether output file was opened successfully:
   if ( !outputFile )  {
      cout << "Cannot write to file " << filename << "." << endl;
      return 1;
   }  // if

   // Begin reading the input file, one line at a time:
   string line;                     // the line most recently read

   while ( true )  {
      getline( inputFile, line );   // read a line from the file

      if ( ! inputFile )            // if end of file
         break;

      // Output the line most recently read:
      outputFile << line << endl;
   }  // while 

   // Announce completion of output file:
   cout << "File " << filename << " has been created." << endl;

   return 0;
}  // function main