/* Filename:  maketext.cpp

   Author:  Br. David Carlson

   Date:  February 23, 1998

   Last Modified:  November 23, 2001

   This program creates a text file of parts information.  The data for
   each part consists of an ID number, number in stock, price, and
   description, and is read from the keyboard and written to this
   text file, called parts.txt.  Each piece of data is written on a
   new line.  Thus it takes 4 lines to hold the data for one part.

   Tested with:
      Microsoft Visual C++ 6.0
      Microsoft Visual C++ .NET
      g++ under Linux
*/

#include <fstream>   // needed for files
#include "parts.h"  // needed for PartType


const int MaxString = DescripMax;

typedef char StringType[MaxString];


/* Given:   fs   A text file stream already opened for output.
   Task:    To read parts data from the user, writing each piece of
            accumulated data to fs.
   Return:  fs   The modified file stream.
*/
void WriteToFile(fstream & fs)
   {
   int Number;
   PartType Part;

   cout << "Enter a part number (or 0 to exit): ";
   cin >> Number;

   while (Number != 0)
      {
      // Place data into the Part record:
      Part.ID = Number;
      cout << "Enter number in stock: ";
      cin >> Part.NumInStock;
      cout << "Enter price: ";
      cin >> Part.Price;
      cin.get();  // input newline at end of price
      cout << "Enter description: ";
      cin.getline(Part.Descrip, DescripMax);

      // Write the data from the Part record to the file, one field
      // at a time.  Note that we cannot write the whole record to the
      // file (without overloading >> to handle these records).  Also
      // note that instead of storing the data in the Part record, the
      // 4 items could be placed in 4 variables and each of them written
      // to the file.  The text file itself thus contains just lines
      // of text; it does not contain records of data.
      fs << Part.ID << endl
         << Part.NumInStock << endl
         << Part.Price << endl
         << Part.Descrip << endl;
      
      cout << "Enter a part number (or 0 to exit): ";
      cin >> Number;
      }
   }


int main(void)
   {
   fstream PartFile;

   PartFile.open("parts.txt", ios::out);
   if (PartFile.fail())
      {
      cerr << "Could not create file parts.dat" << endl;
      exit(1);
      }

   WriteToFile(PartFile);
   PartFile.close();

   return 0;
   }


