advanced program design with c++

24
Concordia University Department of Computer Science and Software Engineering ADVANCED PROGRAM DESIGN WITH C++ Part 3: Input/Output Joey Paquet, 2007- 2014 1 COMP 345 - Advanced Program Design with C++

Upload: jill

Post on 04-Jan-2016

42 views

Category:

Documents


2 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

ADVANCED PROGRAM DESIGN WITH C++Part 3: Input/Output

Joey Paquet, 2007-2014

1COMP 345 - Advanced Program Design with C++

Page 2: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

INPUT AND OUTPUTstreams and stream operatorskeyboard input – console outputoutput formatting stream directivesfile input/output

Joey Paquet, 2007-2014

2COMP 345 - Advanced Program Design with C++

Page 3: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

• 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 cout object (more later on namespaces)

Input and output: streams

Joey Paquet, 2007-2014

3COMP 345 - Advanced Program Design with C++

Page 4: Advanced Program Design with C++

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++

Page 5: Advanced Program Design with C++

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 if it needs to access private members

Input and output: streams

Joey Paquet, 2007-2014

5Advanced Program Design with C++

Page 6: Advanced Program Design with C++

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++

Page 7: Advanced Program Design with C++

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++

Page 8: Advanced Program Design with C++

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++

Page 9: Advanced Program Design with C++

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++

Page 10: Advanced Program Design with C++

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++

Page 11: Advanced Program Design with C++

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 : ifstream• File output : ofstream• 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.

File input/output

Joey Paquet, 2007-2014

11COMP 345 - Advanced Program Design with C++

Page 12: Advanced Program Design with C++

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 modechar ch {‘A’};ofstream output(“myFile.txt”);output.put(ch);

• getline(): read a string from a file in input text mode from the current position to a delimiter characterstring 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++

Page 13: Advanced Program Design with C++

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++

Page 14: Advanced Program Design with C++

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 operationsfilestream.close();…//do other thingsfilestream.open("scores.txt“, ios::in);…//input operationsfilestream.close();

File input/output: open/close a file

Joey Paquet, 2007-2014

14COMP 345 - Advanced Program Design with C++

Page 15: Advanced Program Design with C++

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++

Page 16: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

#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;}

File input/output: text file output example

Joey Paquet, 2007-2014

16COMP 345 - Advanced Program Design with C++

Page 17: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

#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;}

File input/output: text file output example

Joey Paquet, 2007-2014

17COMP 345 - Advanced Program Design with C++

Page 18: Advanced Program Design with C++

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 setbad() returns true if the badbit flag is setgood() returns true is the goodbit flag is setclear() clear all stream state flags

ios::eofbit set when the end of an input stream is reachedios::failbit set when an operation on the stream has failedios::hardfail set when an unrecovered error has occurredios::badbit set when an invalid operation has been attemptedios::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++

Page 19: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

#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;

}

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;

}

Page 20: Advanced Program Design with C++

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 • Boost’s Serialization

File input/output: serialization

Joey Paquet, 2007-2014

20COMP 345 - Advanced Program Design with C++

Page 21: Advanced Program Design with C++

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)

Page 22: Advanced Program Design with C++

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 functionclass 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

Page 23: Advanced Program Design with C++

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;

Page 24: Advanced Program Design with C++

Concordia University

Department of Computer Science and Software Engineering

• Y. Daniel Liang, Introduction to Programming with C++ (Chapter 1, 13), Pearson, 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

References

Joey Paquet, 2007-2014

24Advanced Program Design with C++