Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology
Outlines Default Memberwise Assignment Union Introducing enum File Processing Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File 2
Default Memberwise Assignment 3 Assigning objects Assignment operator (=) Can assign one object to another of same type Default: memberwise assignment Each right member assigned individually to left member Passing, returning objects Objects passed as function arguments Objects returned from functions Default: pass-by-value Copy of object passed, returned Copy constructor o Copy original values into new object
4 1 // Demonstrating that class objects can be assigned 2 // to each other using default memberwise assignment. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // class Date definition 7 class Date { 8 public: 9 Date( int = 1, int = 1, int = 1990 ); // default constructor 10 void print(); 11 private: 12 int month; 13 int day; 14 int year; 15 }; // end class Date
5 16 // Date constructor with no range checking 17 Date::Date( int m, int d, int y ) 18 { 19 month = m; 20 day = d; 21 year = y; 22 } // end Date constructor 23 // print Date in the format mm-dd-yyyy 24 void Date::print() 25 { 26 cout << month << '-' << day << '-' << year; 27 } // end function print 28 int main() 29 { 30 Date date1( 7, 4, 2002 ); 31 Date date2; // date2 defaults to 1/1/1990
32 cout << "date1 = "; 33 date1.print(); 34 cout << "\ndate2 = "; 35 date2.print(); 36 date2 = date1; // default memberwise assignment 37 cout << "\n\nafter default memberwise assignment, date2 = "; 38 date2.print(); 39 cout << endl; 40 return 0; 41 } // end main date1 = 7-4-2002 date2 = 1-1-1990 After default memberwise assignment, date2 = 7-4-2002 6
Union Union Memory that contains a variety of objects Data members share space Only contains one data member at a time Only the last data member defined can be accessed Declaration same as class or struct union Number { }; int x; float y; Union myobject; 7
8 1 // Fig. 20.8: fig20_08.cpp 2 // An example of a union. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // define union Number 7 union Number { 8 int integer1; 9 double double1; 10 }; // end union Number 11 int main() 12 { 13 Number value; // union variable 14 value.integer1 = 100; // assign 100 to member integer1 15 cout << "Put a value in the integer member\n" 16 << "and print both members.\nint: " 17 << value.integer1 << "\ndouble: " << value.double1 18 << endl;
19 value.double1 = 100.0; // assign 100.0 to member double1 20 cout << "Put a value in the floating member\n" 21 << "and print both members.\nint: " 22 << value.integer1 << "\ndouble: " << value.double1 23 << endl; 24 return 0; 25 } // end main 9 Put a value in the integer member and print both members. int: 100 double: -9.25596e+061 Put a value in the floating member and print both members. int: 0 double: 100
10 1 // Fig. 20.9: fig20_09.cpp 2 // Using an anonymous union. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 int main() 7 { 8 // declare an anonymous union 9 // members integer1, double1 and charptr share the same space 10 union { 11 int integer1; 12 double double1; 13 char *charptr; 14 }; // end anonymous union 15 // declare local variables 16 int integer2 = 1; 17 double double2 = 3.3; 18 char *char2ptr = "Anonymous";
19 // assign value to each union member 20 // successively and print each 21 cout << integer2 << ' '; 22 integer1 = 2; 23 cout << integer1 << endl; 24 25 cout << double2 << ' '; 26 double1 = 4.4; 27 cout << double1 << endl; 28 29 cout << char2ptr << ' '; 30 charptr = "union"; 31 cout << charptr << endl; 32 return 0; 33 } // end main 11 1 2 3.3 4.4 Anonymous union
Introducing enum Enumeration Set of integers with identifiers enum typename {constant1, constant2 }; Constants start at 0 (default), incremented by 1 Constants need unique names Cannot assign integer to enumeration variable Must use a previously defined enumeration type Example enum Status {CONTINUE, WON, LOST}; Status enumvar; enumvar = WON; // cannot do enumvar = 1 12
Introducing enum 13 Enumeration constants can have preset values enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; Starts at 1, increments by 1 Next: craps simulator Roll two dice 7 or 11 on first throw: player wins 2, 3, or 12 on first throw: player loses 4, 5, 6, 8, 9, 10 Value becomes player's "point" Player must roll his point before rolling 7 to win
14 1 // Fig. 3.10: fig03_10.cpp 2 // Craps. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // contains function prototypes for functions srand and rand 7 #include <cstdlib> 8 #include <ctime> // contains prototype for function time 9 int rolldice( void ); // function prototype 10 int main() 11 { 12 // enumeration constants represent game status 13 enum Status { CONTINUE, WON, LOST }; 14 int sum; 15 int mypoint; 16 Status gamestatus; // can contain CONTINUE, WON or LOST
15 17 // randomize random number generator using current time 18 srand( time( 0 ) ); 19 sum = rolldice(); // first roll of the dice 20 // determine game status and point based on sum of dice 21 switch ( sum ) { 22 // win on first roll 23 case 7: 24 case 11: 25 gamestatus = WON; 26 break; 27 // lose on first roll 28 case 2: 29 case 3: 30 case 12: 31 gamestatus = LOST; 32 break;
16 33 // remember point 34 default: 35 gamestatus = CONTINUE; 36 mypoint = sum; 37 cout << "Point is " << mypoint << endl; 38 break; // optional 39 } // end switch 40 // while game not complete... 41 while ( gamestatus == CONTINUE ) { 42 sum = rolldice(); // roll dice again 43 // determine game status 44 if ( sum == mypoint ) // win by making point 45 gamestatus = WON; 46 else 47 if ( sum == 7 ) // lose by rolling 7 48 gamestatus = LOST; 49 } // end while
17 50 // display won or lost message 51 if ( gamestatus == WON ) 52 cout << "Player wins" << endl; 53 else 54 cout << "Player loses" << endl; 55 return 0; // indicates successful termination 56 } // end main 57 // roll dice, calculate sum and display results 58 int rolldice( void ) 59 { 60 int die1; 61 int die2; 62 int worksum; 63 die1 = 1 + rand() % 6; // pick random die1 value 64 die2 = 1 + rand() % 6; // pick random die2 value 65 worksum = die1 + die2; // sum die1 and die2
66 // display results of this roll 67 cout << "Player rolled " << die1 << " + " << die2 68 << " = " << worksum << endl; 69 return worksum; // return sum of dice 70 } // end function rolldice Player rolled 2 + 5 = 7 Player wins Player rolled 6 + 6 = 12 Player loses Player rolled 3 + 3 = 6 Point is 6 Player rolled 5 + 3 = 8 Player rolled 4 + 5 = 9 Player rolled 2 + 1 = 3 Player rolled 1 + 5 = 6 Player wins 18
Player rolled 1 + 3 = 4 Point is 4 Player rolled 4 + 6 = 10 Player rolled 2 + 4 = 6 Player rolled 6 + 4 = 10 Player rolled 2 + 3 = 5 Player rolled 2 + 4 = 6 Player rolled 1 + 1 = 2 Player rolled 4 + 4 = 8 Player rolled 4 + 3 = 7 Player loses 19
File Processing Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical disk, tapes 20
Data Hierarchy From smallest to largest Bit (binary digit) 1 or 0 Everything in computer ultimately represented as bits Cumbersome for humans to use Character set Digits, letters, symbols used to represent data Every character represented by 1's and 0's Byte: 8 bits Can store a character (char) 21
Data Hierarchy From smallest to largest (continued) Field: group of characters with some meaning Your name Record: group of related fields struct or class in C++ Each field associated with same employee Record key: field used to uniquely identify record File: group of related records Sequential file: records stored by key Database: group of related files 22
Data Hierarchy Sally Tom Judy Iris Randy Black Blue Green Orange Red File Judy Judy 01001010 Green Field Byte (ASCII character J) Record 1 Bit 23
Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker 0 1 2 3 4 5 6 7 8 9... n-1... end-of-file marker When file opened Object created, stream associated with it cin, cout, etc. created when <iostream> included Communication between program and file/device 24
Files and Streams To perform file processing Include <iostream> and <fstream> Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) 25
Creating a Sequential-Access File C++ imposes no structure on file Concept of "record" must be implemented by programmer To open file, create objects Classes ifstream (input only) ofstream (output only) fstream (I/O) Constructors take file name and file-open mode ofstream outclientfile( "filename", fileopenmode ); To attach a file later Ofstream outclientfile; outclientfile.open( "filename", fileopenmode); 26
Creating a Sequential-Access File File-open modes Mode ios::app ios::in ios::out ios::binary Description Write all output to the end of the file. Open a file for input. Open a file for output. Open a file for binary (i.e., non-text) input or output. ofstream opened for output by default ofstream outclientfile( "clients.dat", ios::out ); ofstream outclientfile( "clients.dat"); 27
Creating a Sequential-Access File Operations Overloaded operator!!outclientfile Returns nonzero (true) if badbit or failbit set Opened non-existent file for reading, wrong permissions Operations Writing to file (just like cout) outclientfile << myvariable Closing file outclientfile.close() Automatically closed when destructor called 28
29 1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::ios; 5 using std::cerr; 6 using std::endl; 7 #include <fstream> 8 using std::ofstream; 9 #include <cstdlib> // exit prototype 10 int main() 11 { 12 // ofstream constructor opens file 13 ofstream outclientfile( "clients.dat", ios::out ); 14 // exit program if unable to create file 15 if (!outclientfile ) { // overloaded! operator 16 cerr << "File could not be opened" << endl; 17 exit( 1 ); 18 } // end if
30 19 cout << "Enter the account, name, and balance." << endl 20 << "Enter end-of-file to end input.\n? "; 21 int account; 22 char name[ 30 ]; 23 double balance; 24 // read account, name and balance from cin, then place in file 25 while ( cin >> account >> name >> balance ) { 26 outclientfile << account << ' ' << name << ' ' << balance 27 << endl; 28 cout << "? "; 29 } // end while 30 return 0; // ofstream destructor closes file 31 } // end main
Enter the account, name, and balance. Enter end-of-file to end input.? 100 Jones 24.98? 200 Doe 345.67? 300 White 0.00? 400 Stone -42.16? 500 Rich 224.62? ^Z 31
Reading Data from a Sequential-Access File Reading files ifstream inclientfile( "filename", ios::in ); Overloaded!!inClientFile tests if file was opened properly while (inclientfile >> myvariable) Stops when EOF found (gets value 0) 32
33 1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::ios; 5 using std::cerr; 6 using std::endl; 7 using std::left; 8 using std::right; 9 using std::fixed; 10 using std::showpoint; 11 #include <fstream> 12 using std::ifstream; 13 #include <iomanip> 14 using std::setw; 15 using std::setprecision; 16 #include <cstdlib> // exit prototype 17 void outputline( int, const char * const, double );
34 18 int main() 19 { 20 // ifstream constructor opens the file 21 ifstream inclientfile( "clients.dat", ios::in ); 22 // exit program if ifstream could not open file 23 if (!inclientfile ) { 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); 26 } // end if 27 int account; 28 char name[ 30 ]; 29 double balance; 30 cout << left << setw( 10 ) << "Account" << setw( 13 ) 31 << "Name" << "Balance" << endl << fixed << showpoint; 32 // display each record in file 33 while ( inclientfile >> account >> name >> balance ) 34 outputline( account, name, balance ); 35 return 0; // ifstream destructor closes the file 36 } // end main
37 // display single record from file 38 void outputline( int account, const char * const name, 39 double balance ) 40 { 41 cout << left << setw( 10 ) << account << setw( 13 ) << name 42 << setw( 7 ) << setprecision( 2 ) << right << balance 43 << endl; 44 45 } // end function outputline Account Name Balance 100 Jones 24.98 200 Doe 345.67 300 White 0.00 400 Stone -42.16 500 Rich 224.62 35