// asterisksRectangle5.cpp
// Prints a few rectangles of asterists to a text file
// Demonstrates an output function using a text file.

#include <iostream>
#include <fstream>

using namespace std;

void printRectangle(int rows, int columns, ofstream& outFile);

/*
 * Prints 3 rectangles of asterisks, of different sizes,
 * to a text file "rectangles.txt."
 *
 * Global variable:
 *    cout -- an ostream object for output to the terminal.
 *           cout is an external variable, declared
 *           in library header file <iostream>.
 */
int main()
{
   // Prepare to write to output file:
   char* outputFilename = "rectangles.txt";   // C-string
   ofstream outputFile;
   outputFile.open(outputFilename);

   // Print the three rectantles to the file:
   printRectangle(5, 15, outputFile);
   outputFile << endl;
   printRectangle(7, 20, outputFile);
   outputFile << endl;
   printRectangle(10, 25, outputFile);

   // Inform user that file has been created.
   cout << "File " << outputFilename
            << " has been created." << endl;

   return 0;
}  // function main

/*
 * void printRectangle(int rows, int columns, ofstream& outFile)
 *
 * Prints a rectangle of asterisks with the specified
 * number of rows and columns, where each cell consists
 * of a single asterisk, preceded by a space.
 *
 * If the parameter values are out of range, an error
 * message is dieplayed to the terminal.
 *
 * Parameters:
 *    rows - the number of rows.
 *                  Must be integer in range [0, 22].
 *    columns - the number of columns
 *                  Must be integer in range [0, 40].
 *    outFile - a file output stream
 *       Preconditions:  outFile has been opened,
 *                   the state of outFile is true, and
 *                   outFile is ready to begin a line.
 *       Postcondition:  The state of outFile is still true,
 *                   and outFile has ended a line.
 *
 * Global variable:
 *    cout -- standard output stream, used for error messages only.
 *       Precondition:  none
 *       Postcondition:  If an error message was printed, cout
 *          has ended a line.  Otherwise, nothing was printed.
 */
void printRectangle(int rows, int columns, ofstream& outFile)
{
   // Check the number of rows:
   if ( rows < 0 || rows > 22 )  {
      cout << "rows=" << rows
                << ", must be in range [0, 22]." << endl;
      return;
   }  // if

   // Check the number of columns:
   if ( columns < 0 || columns > 40 )  {
      cout << "columns=" << columns
                << ", must be in range [0, 40]." << endl;
      return;
   }  // if

   // Print the rectangle to file:
   for ( int i = 0; i < rows; i++ )  {
      for ( int j = 0; j < columns; j++ )
         outFile << " *";
      outFile << endl;
   }  // for i
}  // function printRectangle