1 / 24

Advanced Program Design with C++

Advanced Program Design with C++. Input/Output. Input and output. streams and stream operators k eyboard input – console output output formatting stream directives f ile input/output. Input and output: streams. I/O stream objects cin, cout, cerr

jill
Télécharger la présentation

Advanced Program Design with C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Program Design with C++ Input/Output Joey Paquet, 2007-2014

  2. Input and output streams and stream operators keyboard input – console output output formatting stream directives file input/output Joey Paquet, 2007-2014

  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 canuse the I/O objects cin, cout, cerr or • #include <iostream>using std::cout; • To include only the coutobject (more later on namespaces) Joey Paquet, 2007-2014

  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) cout << numberOfGames << " games played."; • 2 values are outputted: • value of variable numberOfGames, • literal string " games played."; • coutis a stream,<<is a stream operator to output to the stream. • Similar streams exist for file input/output (see later) Joey Paquet, 2007-2014

  5. Input and output: streams • To enable a user-defined type to be outputted to a stream, the << operator must be overloaded to accept this type as an operand. • May be overloaded as a free operator: • Or as a friend operator to the class of it needs to access private members Joey Paquet, 2007-2014

  6. 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 World\n"; • Sends string "Hello World"to display, and escape sequence "\n", skipping to next line cout << "Hello World" << endl; • Same result as above Joey Paquet, 2007-2014

  7. 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 Joey Paquet, 2007-2014

  8. 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 Joey Paquet, 2007-2014

  9. Error output stream • Output with cerr • cerr works same as cout • Provides mechanism for distinguishingbetween regular output and error output Joey Paquet, 2007-2014

  10. Keyboard input stream • cinfor 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 Joey Paquet, 2007-2014

  11. 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. Joey Paquet, 2007-2014

  12. 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(“myFile.txt”); ch = input.get(); • put(): write a single character from a file in output text mode char ch {‘A’}; ofstream output(“myFile.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(“myFile.txt”); getline(input, str, ‘\t’); Joey Paquet, 2007-2014

  13. 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 • ofstreamoutputfilestream; outputfilestream.open("scores.txt"); • ofstreamoutputfilestream("scores.txt"); … outputfilestream.close(); • Input • ifstreaminputfilestream; infilestream.open("scores.txt"); • ifstreaminputfilestream("scores.txt"); … inputfilestream.close(); Joey Paquet, 2007-2014

  14. 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(); Joey Paquet, 2007-2014

  15. File input/output: file modes ios::in Opens a file for input. ios::out Opens a file for output. ios::app Appends all output to the end of the file. ios::ate 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::trunc 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. Joey Paquet, 2007-2014

  16. 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; } Joey Paquet, 2007-2014

  17. File input/output: text file output example #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream input("scores.txt"); string firstName, lastName; char mi; int score; input >> firstName >> mi >> lastName >> score; cout << firstName << " " << mi << " " << lastName << " " << score << endl; input >> firstName >> mi >> lastName >> score; cout << firstName << " " << mi << " " << lastName << " " << score << endl; input.close(); cout << "Done" << endl; return 0; } Joey Paquet, 2007-2014

  18. File input/output: stream states and stream states functions eof() returns true if the eofbit flag is set. fail() returns true if the failbit or hardfail flag is set bad() returns true if the badbit flag is set good() returns true is the goodbit flag is set clear() clear all stream state flags ios::eofbit set when the end of an input stream is reached ios::failbit set when an operation on the stream has failed ios::hardfail set when an unrecovered error has occurred ios::badbit set when an invalid operation has been attempted ios::goodbit set if none of the preceding bits is set Joey Paquet, 2007-2014

  19. File input/output: stream states and stream states functions example void showState(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; } #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; showState(inout); inout.close(); inout.open("temp.txt", ios::in); string city; inout >> city; cout << "End of file (no errors)" << endl; showState(inout); inout.close(); inout >> city; cout << "Bad operation (errors)" << endl; showState(inout); return 0; } Joey Paquet, 2007-2014

  20. 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 Joey Paquet, 2007-2014

  21. File input/output: MFC serialization • In each class that we want to serialize, in the cpp file: • implement the Serialize member function: #include "DerivedRectangleFromAbstractGeometricObject.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) //! 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(). GeometricObject::Serialize(ar); // Serialize dynamic members and other raw data if (ar.IsStoring()) // if the Carchive stream is open for output { ar << width; // need to overload the << operator for your own classes ar << height; // when you want to serialize them as part of an object } else // if the Carchive stream is open for input { ar >> width; ar >> height; } } Joey Paquet, 2007-2014

  22. File input/output: MFC serialization • In header file: //! @file //! @brief Header file for DerivedJRectangleFromAbstractGeometricObject.cpp //! #ifndef JRectangle_H #define JRectangle_H #include "AbstractGeometricObject.h" //! Rectangle class that is a subclass of the GeometricObject class //! It needs to be a subclass of CObject in order to be serializable, and implement //! a Serialize() member function class JRectangle : public GeometricObject { public: JRectangle(); JRectangle(double width, double height); JRectangle(double width, double height, const string& color, bool filled); double getWidth() const; void setWidth(double); double getHeight() const; void setHeight(double); double getArea() const; double getPerimeter() const; virtual void Serialize(CArchive& ar); private: double width; double height; protected: DECLARE_SERIAL(JRectangle); }; #endif Joey Paquet, 2007-2014

  23. File input/output: MFC serialization • To use the serialization-enabled class: int main() { CFiletheFile; //open a file in output mode theFile.Open(_T("CArchiveTest.txt"), CFile::modeCreate | CFile::modeWrite); //create a Carchive stream and connect it to the file CArchive archive(&theFile, 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(); theFile.Close(); CFiletheOtherFile; //open a file in input mode theOtherFile.Open(_T("CArchiveTest.txt"), CFile::modeRead); //Create a CArchive and connect it to the file CArchiveotherArchive(&theOtherFile, CArchive::load); Circle *circle2 = new Circle(); JRectangle *JRect2 = new JRectangle(); //Serialize the objects out from the file circle2->Serialize(otherArchive); JRect2->Serialize(otherArchive); delete circle2; delete JRect2; otherArchive.Close(); theOtherFile.Close(); return 0; Joey Paquet, 2007-2014

  24. 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/00hh13h0.aspx • Microsoft Developer Network. Serialization in MFC. http://msdn.microsoft.com/en-us/library/6bz744w8.aspx • Microsoft Developer Network. Storing and Loading CObjects via an Archive. http://msdn.microsoft.com/en-us/library/3bfsbt0t.aspx Joey Paquet, 2007-2014

More Related