COMP 345 Advanced Program Design with C 1

  • Slides: 23
Download presentation
COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Input/Output Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 2 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 2 Click to edit Master title style INPUT AND OUTPUT streams and stream operators keyboard input – console output formatting stream directives file input/output Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 3 Input and output: streams •

COMP 345 - Advanced Program Design with C++ 3 Input and output: streams • I/O stream objects cin, cout, cerr • Defined in the C++ library called <iostream> • Must have these lines (called pre-processor directives) near start of file: • #include <iostream> using namespace std; • Tells C++ to use appropriate library so we can use the I/O objects cin, cout, cerr or • #include <iostream> using std: : cout; • To include only the cout object (more later on namespaces) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 4 Input and output: streams •

COMP 345 - Advanced Program Design with C++ 4 Input and output: streams • What can be outputted? • Any data can be outputted to display screen • • Variables Constants Literals Expressions (which can include all of above) • To enable a user-defined type to be outputted to a stream, it must implement the to. String() method cout << number. Of. Games << " games played. "; • 2 values are outputted: • value of variable number. Of. Games, • literal string " games played. "; • cout is a stream, << is a stream operator to output to the stream. • Similar streams exist for file input/output (see later) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 5 End of line in output

COMP 345 - Advanced Program Design with C++ 5 End of line in output • New lines in output • Recall: "n" is escape sequence for the char "newline" • A second method: object endl • Examples: cout << "Hello Worldn"; • Sends string "Hello World" to display, and escape sequence "n", skipping to next line cout << "Hello World" << endl; • Same result as above Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 6 Stream formatting directives • Formatting

COMP 345 - Advanced Program Design with C++ 6 Stream formatting directives • Formatting numeric values for output • Values may not display as you’d expect! cout << "The price is $" << price << endl; • If price (declared double) has value 78. 5, you might get: • The price is $78. 500000 or: • The price is $78. 5 • We must explicitly tell C++ how to output specially-formatted numbers in our programs Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 7 Stream formatting directives • Stream

COMP 345 - Advanced Program Design with C++ 7 Stream formatting directives • Stream formatting directives to force decimal sizes: cout. setf(ios: : fixed); cout. setf(ios: : showpoint); cout. precision(2); • These directives force all future cout’ed values: • To have exactly two digits after the decimal point • Example: cout << "The price is $" << price << endl; • Now results in the following: The price is $78. 50 • Can be modified later • Many other kinds of directives exist Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 8 Error output stream • Output

COMP 345 - Advanced Program Design with C++ 8 Error output stream • Output with cerr • cerr works same as cout • Provides mechanism for distinguishing between regular output and error output Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 9 Keyboard input stream • cin

COMP 345 - Advanced Program Design with C++ 9 Keyboard input stream • cin for input (from the keyboard), cout for output (to the screen) • Differences: • ">>" (extraction operator) points opposite • Think of it as "pointing toward where the data goes" • Object name "cin" used instead of "cout" • No literals allowed for cin • Must input "to a variable" • cin >> num; • Waits on-screen for keyboard entry • Value entered at keyboard is "assigned" to num Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 10 File input/output • Similar to

COMP 345 - Advanced Program Design with C++ 10 File input/output • Similar to cin/cout streams, there are streams for input/output from/to files • File input : istream • File output : ostream • Part of library <fstream> • May use the same stream operators and formatting directives • They are more complex to use compared to cin/cout: • Choice between different modes e. g text, binary, random-access • Different operators to use for different modes • May have to check for various stream states, which are set for example when operating on a non-existing file, or reaching the end of a file. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 11 File input/output: Text files •

COMP 345 - Advanced Program Design with C++ 11 File input/output: Text files • Text file is the most simple file read/write mode • Very similar to cin/cout • Use << operator to write • Use >> operator to read • Can also use • get(): read a single character from a file in input text mode char ch; ifstream input(“my. File. txt”); ch = input. get(); • put(): write a single character from a file in output text mode char ch {‘A’}; ofstream output(“my. File. txt”); output. get(ch); • getline(): read a string from a file in input text mode from the current position to a delimiter character string str; ifstream input(“my. File. txt”); getline(input, str, ‘t’); Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 12 File input/output: open/close a file

COMP 345 - Advanced Program Design with C++ 12 File input/output: open/close a file • In order to read/write to a file, it needs to be opened before and to attach a stream to it, and closed once the operation is over. • Output 1. ofstream outputfilestream; outputfilestream. open("scores. txt"); 2. ofstream outputfilestream("scores. txt"); … outputfilestream. close(); • Input • ifstream inputfilestream; infilestream. open("scores. txt"); 2. ifstream inputfilestream("scores. txt"); … inputfilestream. close(); Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 13 File input/output: open/close a file

COMP 345 - Advanced Program Design with C++ 13 File input/output: open/close a file • An fstream object can also be used, but in this case, file modes need to be specified: fstream filestream; filestream. open("scores. txt“, ios: : out); …//output operations filestream. close(); …//do other things filestream. open("scores. txt“, ios: : in); …//input operations filestream. close(); Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 14 File input/output: file modes Opens

COMP 345 - Advanced Program Design with C++ 14 File input/output: file modes Opens a file for input. Opens a file for output. Appends all output to the end of the file. Opens a file for output. If the file already exists, move to the end of the file. Data can be written anywhere in the file. ios: : truct Discards the file’s contents if the file already exists. (This is the default action for ios: out). ios: : binary Opens a file for binary input and output. ios: : in ios: : out ios: : app ios: : ate Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 15 File input/output: text file output

COMP 345 - Advanced Program Design with C++ 15 File input/output: text file output example #include <iostream> #include <fstream> using namespace std; int main() { ofstream output; // Create/open a file output. open("scores. txt"); // Write two lines output << "John" << "T" << "Smith" << " " << 90 << endl; output << "Eric" << "K" << "Jones" << " " << 85 << endl; // Close the file output. close(); cout << "Done" << endl; return 0; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 16 File input/output: text file output

COMP 345 - Advanced Program Design with C++ 16 File input/output: text file output example #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream input("scores. txt"); string first. Name, last. Name; char mi; int score; input >> first. Name >> mi >> last. Name >> score; cout << first. Name << " " << mi << " " << last. Name << " " << score << endl; input. close(); cout << "Done" << endl; return 0; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 17 File input/output: stream states and

COMP 345 - Advanced Program Design with C++ 17 File input/output: stream states and stream states functions eof() fail() bad() good() clear() returns true if the eofbit flag is set. returns true if the failbit or hardfail flag is set returns true if the badbit flag is set returns true is the goodbit flag is set clear all stream state flags ios: : eofbit ios: : failbit ios: : hardfail ios: : badbit ios: : goodbit set when the end of an input stream is reached set when an operation on the stream has failed set when an unrecovered error has occurred set when an invalid operation has been attempted set if none of the preceding bits is set Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 18 File input/output: stream states and

COMP 345 - Advanced Program Design with C++ 18 File input/output: stream states and stream states functions example #include <iostream> #include <fstream> #include <string> using namespace std; int main() { fstream inout; inout. open("temp. txt", ios: : out); inout << "Dallas"; cout << "Normal operation (no errors)" << endl; show. State(inout); inout. close(); void show. State(const fstream& stream) { cout << "Stream status: " << endl; cout << " eof(): " << stream. eof() << endl; cout << " fail(): " << stream. fail() << endl; cout << " bad(): " << stream. bad() << endl; cout << " good(): " << stream. good() << endl; } inout. open("temp. txt", ios: : in); string city; inout >> city; cout << "End of file (no errors)" << endl; show. State(inout); inout. close(); inout >> city; cout << "Bad operation (errors)" << endl; show. State(inout); return 0; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 19 File input/output: serialization • Sometimes

COMP 345 - Advanced Program Design with C++ 19 File input/output: serialization • Sometimes you may want to save objects to a file, or in general do what is called “object serialization” i. e. transform an object into a stream of bytes that can be transferred and/or saved/retrieved. • Java provides object serialization though the java. io. Serializable interface. • C++ does not provide such native solution, but there are two well-recognized ways to achieve that though libraries: • MFC’s CObject: : Serialize() function • Boost’s Serialization Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 20 File input/output: MFC serialization • In each class

Advanced Program Design with C++ 20 File input/output: MFC serialization • In each class that we want to serialize, in the cpp file: #include "Derived. Rectangle. From. Abstract. Geometric. Object. h" • //Signify to MFC serialization that objects of this class are serializable //Parameter 1 : Name of the class //Parameter 2 : Name of the first non-abstract class up on the inheritance chain //Parameter 3 : Class schema version name. Must use same value across classes. IMPLEMENT_SERIAL(JRectangle, CObject, 1) • implement the Serialize member function: //! Serialize a Rectangle to/from a MFC CArchive //! @param ar : CArchive object to serialize to/from //! @ return none //! void JRectangle: : Serialize(CArchive& ar) { // Always call base class Serialize(). Geometric. Object: : Serialize(ar); // Serialize dynamic members and other raw data if (ar. Is. Storing()) { ar << width; ar << height; } else { ar >> width; ar >> height; } } Concordia University // if the Carchive stream is open for output // need to overload the << operator for your own classes // when you want to serialize them as part of an object // if the Carchive stream is open for input Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 21 File input/output: MFC serialization • In header file:

Advanced Program Design with C++ 21 File input/output: MFC serialization • In header file: //! @file //! @brief Header file for Derived. JRectangle. From. Abstract. Geometric. Object. cpp //! #ifndef JRectangle_H #define JRectangle_H #include "Abstract. Geometric. Object. h" //! Rectangle class that is a subclass of the Geometric. Object class //! It needs to be a subclass of CObject in order to be serializable, and implement //! a Serialize() member function class JRectangle : public Geometric. Object { public: JRectangle(); JRectangle(double width, double height, const string& color, bool filled); double get. Width() const; void set. Width(double); double get. Height() const; void set. Height(double); double get. Area() const; double get. Perimeter() const; virtual void Serialize(CArchive& ar); private: double width; double height; protected: DECLARE_SERIAL(JRectangle); }; #endif Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 22 File input/output: MFC serialization • To use the

Advanced Program Design with C++ 22 File input/output: MFC serialization • To use the serialization-enabled class: int main() { CFile the. File; //open a file in output mode the. File. Open(_T("CArchive. Test. txt"), CFile: : mode. Create | CFile: : mode. Write); //create a Carchive stream and connect it to the file CArchive archive(&the. File, CArchive: : store); Circle *circle = new Circle(5, "black", true); JRectangle *JRect = new JRectangle(5, 3, "red", true); //Serialize the objects into the file circle->Serialize(archive); JRect->Serialize(archive); delete circle; delete JRect; archive. Close(); the. File. Close(); CFile the. Other. File; //open a file in input mode the. Other. File. Open(_T("CArchive. Test. txt"), CFile: : mode. Read); //Create a CArchive and connect it to the file CArchive other. Archive(&the. Other. File, CArchive: : load); Circle *circle 2 = new Circle(); JRectangle *JRect 2 = new JRectangle(); //Serialize the objects out from the file circle 2 ->Serialize(other. Archive); JRect 2 ->Serialize(other. Archive); delete circle 2; delete JRect 2; other. Archive. Close(); the. Other. File. Close(); return 0; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 23 References • Y. Daniel Liang, Introduction to Programming

Advanced Program Design with C++ 23 References • Y. Daniel Liang, Introduction to Programming with C++ (Chapter 1, 13), Peason, • • 2014. Bjarne Stroustrup, The C++ Programming Language (Chapter 30, 38), Addison. Wesley, 2013. Microsoft Developer Network. Serialization: Making a Serializable Class. http: //msdn. microsoft. com/en-us/library/00 hh 13 h 0. aspx Microsoft Developer Network. Serialization in MFC. http: //msdn. microsoft. com/en-us/library/6 bz 744 w 8. aspx Microsoft Developer Network. Storing and Loading CObjects via an Archive. http: //msdn. microsoft. com/en-us/library/3 bfsbt 0 t. aspx Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014