COMP345: Advanced Program Design With C++ Input/Output

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

COMP345:

Advanced Program Design with C++

Lecture 3
Input/Output
Fall 2020
Department of Computer Science and Software Engineering
Concordia University
Contents
❑ streams and stream operators
▪ keyboard input – console output
▪ output formatting stream directives
❑ file input/output
❑ MFC serialization
Advanced Program Design with C++ 3

Input and output: streams


▪ C++ uses streams for input/output.
▪ C++ programs can also use C-style input/output, which don’t use streams.

▪ Streams are objects that are defined to handle a device on which input or output operations are
performed.

▪ Streams allow C++ programs to interact with external entities controlled by the operating system,
such as:
▪ program execution console
▪ keyboard
▪ files

▪ Other external entities such as network sockets are not provided by basic C++ stream classes, but
are available in various libraries (e.g. Boost).

Joey Paquet, 2007-2020


Advanced Program Design with C++ 4

Input and output: streams


▪ I/O stream objects cin, cout, cerr
▪ Defined in the C++ library called <iostream>
▪ Must have these lines (pre-processor directives) :

#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

▪ cout is an object that is an instance of the ostream class, defined in the iostream
library.

Joey Paquet, 2007-2020


Advanced Program Design with C++ 5

Input and output: streams


▪ What can be outputted?
▪ Any data can be outputted to a stream
▪ Variables
▪ Constants
▪ Literals
▪ Results of expressions

cout << numberOfGames + 1 << " games played.";

▪ 2 values are outputted:


▪ value of the expression numberOfGames + 1
▪ literal string " games played."

▪ cout is a stream, << is the stream insertion operator that is used to output to the
stream.

Joey Paquet, 2007-2020


Advanced Program Design with C++ 6

Input and output: streaming user-defined data types


▪ 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

▪ Operators and friends will be covered in detail later

Joey Paquet, 2007-2020


Advanced Program Design with C++ 7

End of line in output


▪ New lines in output
▪ Recall in C: "\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

▪ endl is a stream manipulator, which is a directive sent to a stream that instructs the
stream’s behavior.

▪ There are many stream manipulators, which we shall not cover here in detail.

Joey Paquet, 2007-2020


Advanced Program Design with C++ 8

Stream manipulators
▪ Formatting numeric values for output

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 using stream manipulators.

Joey Paquet, 2007-2020


Advanced Program Design with C++ 9

Stream manipulators
▪ Stream manipulators to force decimal sizes:

cout << fixed << showpoint << setprecision(2);

▪ These directives force all future cout’ed floating point values to have exactly two digits
after the decimal point:
▪ fixed: set the stream to manipulate floating point numbers to be represented
as fixed-point representation (as opposed to scientific notation, or integer
notation)
▪ showpoint: show trailing zeroes in after the point, even if there are none.
▪ setprecision(n): set the number of digits of precision used for floating point
numbers.

cout << "The price is $" << price << endl;


The price is $78.50

Joey Paquet, 2007-2020


Advanced Program Design with C++ 10

Keyboard input stream


▪ Use cin for input from the keyboard
▪ cin is an object that is an instance of the istream class.
▪ Uses ">>" (stream extraction operator)
▪ Its right-hand-side argument must be a variable.

cin >> num;

▪ Waits on-screen for keyboard entry (reads keyboard until <enter>)


▪ Value entered at keyboard is "assigned" to the variable num
▪ If the value is of wrong type, the operation fails and/or an exception is thrown.

▪ Different C-style functions/operators can be used, e.g.:


▪ getline(istream, string)
▪ getc(istream, char)
▪ cin.get()

Joey Paquet, 2007-2020


Contents
❑ streams and stream operators
▪ keyboard input – console output
▪ output formatting stream directives
❑ file input/output
❑ MFC serialization
Advanced Program Design with C++ 12

File input/output
▪ 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.

Joey Paquet, 2007-2020


Advanced Program Design with C++ 13

File input/output: Text files


▪ Text file is the simplest file read/write mode
▪ Very similar to cin/cout
▪ Use << operator to write
▪ Use >> operator to read
▪ Can also use C-style functions
▪ 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.put(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-2020
Advanced Program Design with C++ 14

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 (1). This can be optionally done as the stream variable is declared (2).
▪ 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();

Joey Paquet, 2007-2020


Advanced Program Design with C++ 15

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


Advanced Program Design with C++ 16

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


Advanced Program Design with C++ 17

File input/output: text file output example



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();

Joey Paquet, 2007-2020


Advanced Program Design with C++ 18

File input/output: text file input example


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();

…OR…

string firstName, lastName; char mi; int score;


ifstream input("scores.txt");
input >> firstName >> mi >> lastName >> score;
while (!input.eof()) {
cout << firstName << " " << mi << " " << lastName << " " << score << endl;
input >> firstName >> mi >> lastName >> score;
}
input.close();

Joey Paquet, 2007-2020


Advanced Program Design with C++ 19

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


Advanced Program Design with C++ 20

File input/output: stream states and stream states functions


example
#include <iostream> void showState(const fstream& stream)
#include <fstream> {
#include <string> cout << "Stream status: " << endl;
using namespace std; cout << " eof(): " << stream.eof() << endl;
cout << " fail(): " << stream.fail() << endl;
int main() cout << " bad(): " << stream.bad() << endl;
{ cout << " good(): " << stream.good() << endl;
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-2020


Contents
❑ streams and stream operators
❑ keyboard input – console output
❑ output formatting stream directives
❑ file input/output
❑ MFC serialization
Advanced Program Design with C++ 22

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
▪ The following serves as an example to demonstrate:
▪ How to use MFC serialization.
▪ That using libraries can be very peculiar.

Joey Paquet, 2007-2020


Advanced Program Design with C++ 23
File input/output: MFC serialization
▪ In each class that we want to serialize, in the cpp file:
#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)

▪ 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().
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-2020
Advanced Program Design with C++ 24

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


Advanced Program Design with C++ 25

File input/output: MFC serialization


▪ To use the serialization-enabled class:
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;
Joey Paquet, 2007-2020
References
▪ 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
▪ Cplusplus.com. Input/output.
▪ Barnette, McQuain. C++ Input/Output: Streams. Virginia Tech.
▪ Kurt McMahon. Output Formatting. Northern Illinois University.
▪ Joey Paquet COMP345 course Notes Concordia university.

You might also like