home *** CD-ROM | disk | FTP | other *** search
/ Microsoftware Monthly 19…2 Programming Power Tools / MASO9512.ISO / cpptutor / cpptutor.arj / EXAMPLES / EX0801.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1993-10-14  |  1.9 KB  |  54 lines

  1. // \EXAMPLES\EX0801.CPP
  2. // main program to demonstrate friend functions
  3. //---------------------------------------------------------
  4. // files in this example:
  5. // %F,15,EX0801.H%EX0801.H        definition of Fraction class
  6. // EX0801.CPP      main program
  7. //---------------------------------------------------------
  8. #include <iostream.h>                // stream I/O
  9. #include <strstrea.h>                // #include <strstream.h>
  10. #include "EX0801.H"
  11.  
  12. void print(const Fraction& f);
  13. void read(Fraction& f);
  14.  
  15. void main()
  16. {  Fraction f;                             // declare a fraction
  17.    cout << "Enter a fraction n/d:  ";
  18.    read(f);                                // read a fraction
  19.    cout << "print()\t";
  20.    print(f);                               // output using friend
  21.    cout << endl;
  22.    cout << "display()\t ";
  23.    f.display();                            // output using member
  24.    cout << endl;
  25.    cout << "<<\t";
  26.    cout << f << endl;                      // output using <<
  27. }
  28.  
  29. //  functions -- friends of the fraction class
  30.  
  31. void print(const Fraction& f)
  32. {  cout << f.num << "/" << f.denom;
  33. }
  34.  
  35. void read(Fraction& f)
  36. {  char c;                            // to hold the '/'
  37.    f.num = 0;                         // default numerator
  38.    f.denom = 1;                       // default denominator
  39.    char buffer[20];                   // for reformatting
  40.    ostrstream oss(buffer,26,ios::out);   // in-memory output
  41.    istrstream iss(buffer,26);            // in-memory input
  42.    char token[20];                    // to hold raw input
  43.    cin >> token;                       // read as  string
  44.    oss << token << "/1" << ends;      // write to memory
  45.    iss >> f.num >> c >> f.denom;      // read int-char-int
  46.    if ( c != '/' ) f.denom = 1;       // check syntax n/d
  47.    f.reduce();                        // simplify fraction
  48. }
  49.  
  50. ostream& operator<<( ostream& os, const Fraction& f)
  51. { os << f.num << "/" << f.denom;
  52.   return os;
  53. }
  54.