Download presentation
Presentation is loading. Please wait.
Published byTyler Tyler Modified over 9 years ago
1
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Input/Output Joey Paquet, 2007-2014 1COMP 345 - Advanced Program Design with C++
2
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style INPUT AND OUTPUT streams and stream operators keyboard input – console output output formatting stream directives file input/output Joey Paquet, 2007-2014 2COMP 345 - Advanced Program Design with C++
3
Concordia University Department of Computer Science and Software Engineering I/O stream objects cin, cout, cerr Defined in the C++ library called Must have these lines (called pre-processor directives) near start of file: #include using namespace std; Tells C++ to use appropriate library so we can use the I/O objects cin, cout, cerr or #include using std::cout; To include only the cout object (more later on namespaces) Input and output: streams Joey Paquet, 2007-2014 3COMP 345 - Advanced Program Design with C++
4
Concordia University Department of Computer Science and Software Engineering 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."; cout is a stream, << is a stream operator to output to the stream. Similar streams exist for file input/output (see later) Input and output: streams Joey Paquet, 2007-2014 4COMP 345 - Advanced Program Design with C++
5
Concordia University Department of Computer Science and Software Engineering 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 Input and output: streams Joey Paquet, 2007-2014 5Advanced Program Design with C++
6
Concordia University Department of Computer Science and Software Engineering 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 End of line in output Joey Paquet, 2007-2014 6COMP 345 - Advanced Program Design with C++
7
Concordia University Department of Computer Science and Software Engineering 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 Stream formatting directives Joey Paquet, 2007-2014 7COMP 345 - Advanced Program Design with C++
8
Concordia University Department of Computer Science and Software Engineering 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 Stream formatting directives Joey Paquet, 2007-2014 8COMP 345 - Advanced Program Design with C++
9
Concordia University Department of Computer Science and Software Engineering Output with cerr cerr works same as cout Provides mechanism for distinguishing between regular output and error output Error output stream Joey Paquet, 2007-2014 9COMP 345 - Advanced Program Design with C++
10
Concordia University Department of Computer Science and Software Engineering 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 Keyboard input stream Joey Paquet, 2007-2014 10COMP 345 - Advanced Program Design with C++
11
Concordia University Department of Computer Science and Software Engineering Similar to cin / cout streams, there are streams for input/output from/to files File input : istream File output : ostream Part of library 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. File input/output Joey Paquet, 2007-2014 11COMP 345 - Advanced Program Design with C++
12
Concordia University Department of Computer Science and Software Engineering 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’); File input/output: Text files Joey Paquet, 2007-2014 12COMP 345 - Advanced Program Design with C++
13
Concordia University Department of Computer Science and Software Engineering 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 1. ifstream inputfilestream; infilestream.open("scores.txt"); 2. ifstream inputfilestream("scores.txt"); … inputfilestream.close(); File input/output: open/close a file Joey Paquet, 2007-2014 13COMP 345 - Advanced Program Design with C++
14
Concordia University Department of Computer Science and Software Engineering 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(); File input/output: open/close a file Joey Paquet, 2007-2014 14COMP 345 - Advanced Program Design with C++
15
Concordia University Department of Computer Science and Software Engineering 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. File input/output: file modes Joey Paquet, 2007-2014 15COMP 345 - Advanced Program Design with C++
16
Concordia University Department of Computer Science and Software Engineering #include 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; } File input/output: text file output example Joey Paquet, 2007-2014 16COMP 345 - Advanced Program Design with C++
17
Concordia University Department of Computer Science and Software Engineering #include 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; } File input/output: text file output example Joey Paquet, 2007-2014 17COMP 345 - Advanced Program Design with C++
18
Concordia University Department of Computer Science and Software Engineering 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 File input/output: stream states and stream states functions Joey Paquet, 2007-2014 18COMP 345 - Advanced Program Design with C++
19
Concordia University Department of Computer Science and Software Engineering #include 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; } File input/output: stream states and stream states functions example Joey Paquet, 2007-2014 19COMP 345 - Advanced Program Design with C++ 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; }
20
Concordia University Department of Computer Science and Software Engineering 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 MFC’s CObject::Serialize() function Boost’s Serialization File input/output: serialization Joey Paquet, 2007-2014 20COMP 345 - Advanced Program Design with C++
21
Concordia University Department of Computer Science and Software Engineering In each class that we want to serialize, in the cpp file: implement the Serialize member function: File input/output: MFC serialization Joey Paquet, 2007-2014 21Advanced Program Design with C++ //! 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; } #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)
22
Concordia University Department of Computer Science and Software Engineering In header file: File input/output: MFC serialization Joey Paquet, 2007-2014 22Advanced Program Design with C++ //! @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
23
Concordia University Department of Computer Science and Software Engineering To use the serialization-enabled class: File input/output: MFC serialization Joey Paquet, 2007-2014 23Advanced Program Design with C++ int main() { CFile theFile; //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(); CFile theOtherFile; //open a file in input mode theOtherFile.Open(_T("CArchiveTest.txt"), CFile::modeRead); //Create a CArchive and connect it to the file CArchive otherArchive(&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;
24
Concordia University Department of Computer Science and Software Engineering 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 http://msdn.microsoft.com/en-us/library/00hh13h0.aspx Microsoft Developer Network. Serialization in MFC. http://msdn.microsoft.com/en-us/library/6bz744w8.aspx 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.aspxhttp://msdn.microsoft.com/en-us/library/3bfsbt0t.aspx References Joey Paquet, 2007-2014 24Advanced Program Design with C++
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.