Slide 5.8: A stream file
Slide 5.10: Field structures
Home

Constructors and Operator Overloading


The program below shows how to implement the previous Interface Enter Book Information by using constructor and operator overloading. For the new definition of the insertion operator <<, file << b is to write the contents of a Book object b to the file file.

 ~wenchen/public_html/cgi-bin/351/week5/EnterBooks2.cpp 
#include  <fstream>
#include  <iostream>
#include  <cstring>
  using namespace  std;
class  Book {
  public:
    char  title[51];
    char  ISBN[16];
    char  price[8];
    char  quantity[6];

    Book( char* a, char* b, char* c, char* d ) {
      char  spaces[51] = "                                                  ";
      strcpy  ( title, spaces );
      strncpy ( title, a, strlen( a ) );
      strcpy  ( ISBN, spaces );
      strncpy ( ISBN, b, strlen( b ) );
      strcpy  ( price, spaces );
      strncpy ( price, c, strlen( c ) );
      strcpy  ( quantity, spaces );
      strncpy ( quantity, d, strlen( d ) );
    }
};
ostream&  operator<< ( ostream& outFile, Book& b ) {

  outFile.write( b.title,   50 );
  outFile << "|";
  outFile.write( b.ISBN,    15 );
  outFile << "|";
  outFile.write( b.price,    7 );
  outFile << "|";
  outFile.write( b.quantity, 5 );
  outFile << "|" << endl;
  return( outFile );
}
int  main( int argc, char* argv[ ] ) {
  fstream  file;
  char     title[51], ISBN[16], price[8], quantity[6];
 
  strcpy( title,    argv[1] );
  strcpy( ISBN,     argv[2] );
  strcpy( price,    argv[3] ); 
  strcpy( quantity, argv[4] ); 
  Book  b( title, ISBN, price, quantity );
  file.open( "books.txt", fstream::out | fstream::app );
  file << b;
  file.close( );
}