12
©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects. An object must also be connected to an input/output device or a file on which the physical input/output operations are performed. Four objects, cin, cout, cerr, and clog are predefined in the <iostream> header file. The predefined objects cin is an instance of the class istream and is connected to the standard input device which is the keyboard by default. The predefined object cout is an instance of the class ostream and is connected to the standard output device which is the monitor by default. The predefined objects cerr and clog are instances of the class ostream and are connected to the standard error device which is the monitor by default. The >> operator (also known as the stream extraction operator) is defined on the class istream to input data items of built-in types, strings, and pointer types. The << operator (also known as the stream insertion operator) is defined on the class ostream to output the values of arithmetic, Boolean, character, and string expressions. After each I/O operation on an object instance of a stream class, that object can be in various states. The Boolean-value methods in table IO1 are provided to report the states of these objects. Table IO2 lists some of the most commonly used methods of istream class. In the description provided, _in is an object instance of the istream (or ifstream) class; ch is a char variable, stop is a char literal, variable, or constant; chArray is a char array; and n and offset are integers. Table IO3 lists some of the most commonly used methods of ostream class. In the description provided, _out is an object instance of the ostream (or ofstream) class; ch is a char variable; chArray is a char array; and n and offset are integers. Table IO1 Methods that report the state of an object after an I/O operation Message Returns True if and only if obj.good( ) All is well for stream object obj. obj.bad( ) An unrecoverable error occurred in stream object obj. obj.fail( ) A recoverable error occurred in stream object obj. obj.eof( ) End-of-file mark encountered in stream object obj before finding any data.

Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

  • Upload
    others

  • View
    14

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 325

Input / Output in C++

In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects.

An object must also be connected to an input/output device or a file on which the physical

input/output operations are performed.

Four objects, cin, cout, cerr, and clog are predefined in the <iostream> header file.

The predefined objects cin is an instance of the class istream and is connected to the standard input

device which is the keyboard by default.

The predefined object cout is an instance of the class ostream and is connected to the standard

output device which is the monitor by default.

The predefined objects cerr and clog are instances of the class ostream and are connected to the

standard error device which is the monitor by default.

The >> operator (also known as the stream extraction operator) is defined on the class istream to

input data items of built-in types, strings, and pointer types.

The << operator (also known as the stream insertion operator) is defined on the class ostream to

output the values of arithmetic, Boolean, character, and string expressions.

After each I/O operation on an object instance of a stream class, that object can be in various states.

The Boolean-value methods in table IO1 are provided to report the states of these objects.

Table IO2 lists some of the most commonly used methods of istream class. In the description

provided, _in is an object instance of the istream (or ifstream) class; ch is a char variable, stop is a

char literal, variable, or constant; chArray is a char array; and n and offset are integers.

Table IO3 lists some of the most commonly used methods of ostream class. In the description

provided, _out is an object instance of the ostream (or ofstream) class; ch is a char variable;

chArray is a char array; and n and offset are integers.

Table IO1 Methods that report the state of an object after an I/O operation

Message Returns True if and only if

obj.good( ) All is well for stream object obj.

obj.bad( ) An unrecoverable error occurred in stream object obj.

obj.fail( ) A recoverable error occurred in stream object obj.

obj.eof( ) End-of-file mark encountered in stream object obj before finding any data.

Page 2: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 326

Table IO2 istream class methods

Operation Description

_in.get( ch )

or

ch = _in.get( )

Input a single character (including white space) from _in into ch.

_in.get( chArray, n, stop )

or

_in.get( chArray, n )

Input characters from _in into chArray until n-1 characters are read or the

character stop (default value ‘\n’) is encountered (but not extracted), or the end-

of-file occurs. A null character is added at the end of the input.

_in.getine( chArray, n, stop )

or

_in.getline( chArray, n )

Same as get( ), except that it removes the terminating character stop from _in.

_in.read( chArray, n ) Input characters from _in into chArray until n characters are read or the end-of-

file occurs.

_in.readsome( chArray, n ) Same as read( ), but returns the number of characters extracted.

_in.peek( ) Return the next character to be read from _in, but leave it in the stream.

_in.putback( ch ) Put the character in ch back into _in.

_in.unget( ) Put the most recent character read back into _in.

Table IO3 ostream class methods

Operation Description

_out.put( ch ) Output the single character in ch to _out.

_out.write( chArray, n ) Output n characters of chArray to _out.

_out.flush( ) Empty _out’s output buffer.

Examples

Assume given the following definitions of variables and arrays:

char symb, text[10] = { ‘\0’ }, document[ 80 ] = { ‘\0’ };

1. Code segment to read the string “John Doe” from the keyboard:

cin >> text;

Input: John Doe

Array after the execution of the code:

J o h n \0 \0 \0 \0 \0 \0

Page 3: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 327

2. Code segment to read the string “John Doe” from the keyboard:

for( int c = 0 ; c < 9 ; c++ )

{

cin.get( symb ); // can also be written as: symb = cin.get( );

text[ c ] = symb;

}

Input: John Doe

Array after the execution of the code:

J o h n D o e \0 \0

3. Code segment to read the string “John Doe” from the keyboard:

cin.get( text , 9 , ‘\n’ ); // can also be written as: cin.get( text , 9 );

Input: John Doe

Array after the execution of the code:

J o h n D o e \0 \0

4. Code segment to read a sequence of 79 characters from the keyboard or until the END-OF-FILE

character is entered:

int c = 0 ;

cin.get( symb );

while( c < 79 && !cin.eof( ) )

{

text[ c++ ] = symb;

cin.get( symb );

}

5. Code segment to out the string “Error: invalid character” to the monitor:

cerr >> “Error: invalid character”; // this necessary when you make output redirection

6. Code segment to output the string in the array text[ ] to the monitor:

cout << text; // can also be written as: cout.write( text , 8 );

Page 4: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 328

File Input - Output

File input are performed on object instances of the class ifstream and

File output are performed on object instances of the class ofstream.

ifstream is a derived class of the class istream:

o All the methods of the istream class (including those in tables OI1 and OI2) are also the

methods of the ifstream class.

o The stream extraction operator >> can also be used to perform input from object instances of

the ifstream class.

ofstream is a derived class of the class ostream:

o All the methods of the ostream class (including those in tables OI1 and OI3) are also the

methods of the ofstream class.

o The stream insertion operator << can also be used to perform output to object instances of the

ofstream class.

The definitions of ifstream and ofstream classes are provided in the header file <fstream>:

o You must therefore include this header file in all program in which file I/O are performed.

Formatted output are performed with a file output stream object in the same way that it is done with

cout stream object:

o Just replace cout with the name of your object in the output statement.

You connect an input/output stream object to a file on which the physical input/output

operations are performed by using the open method as follows:

<stream-object>.open( <name-of-file>, <opening-mode>);

Where:

<stream-object> is the name of the stream object.

<name-of-file> is the filename specification of the input/output file.

<opening-mode> is the file-opening mode.

The file-opening modes are listed in table OI4.

Examples

1. // fin is my input stream object and program.dat is my input file

ifstream fin;

fin.open(“progam.dat”, ios::in); or fin.open(“progam.dat”);

Page 5: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 329

2. // fout is my output stream object and program.out is my output file

ofstream fout;

fout.open(“progam.out”, ios::out); or fout.open(“progam.out”);

3. // fapp is my output stream object and program.out is my output file

ofstream fapp;

fapp.open(“progam.out”, ios::app);

After you are done doing I/O operations on an I/O stream object, use the member function close( ) to

close the corresponding file as follows:

<stream-object>.close( );

Examples

1. fin.close( );

2. fout.close( );

3. fapp.close( );

Table IO4

Mode Description

ios :: in This is the default mode for ifstream objects. Open a file for input, non- destructively,

with the read position at the beginning of the file.

ios :: trunc Open a file and delete any contents it contains.

ios :: out This is the default mode for ofstream objects. Open a file for output using ios::trunc.

ios :: app Open a file for output, but non-destructively, with the write position at the end of the file.

ios :: ate Open an existing file with the read position (for ifstream objects) or write position (for

ofstream objects) at the end of the file.

ios :: binary

Open a file for which I/O will be done in binary mode. Bytes are read from the file into

a char array using the read method and written from a char array to the file using the

write method.

Page 6: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 330

Example IO1

ifstream fin; // fin is my input stream object

ofstream fout; // fout is my output stream object

fin.open(“progam.dat”, ios::in); // program.dat is my input file

fout.open(“progam.out”, ios::out); // program.out is my output file

/*-----------------read two integer values from the input file program.dat ---------------------*/

int num1, nm2;

fin >> num1 >> num2;

/*---------compute their sum and write the result in the output file program.out -------------*/

fout << endl << “num1=\t” << num1 << endl << “num2=\t” << num2

<< endl << “Their sum is:\\t” << (num1 + num2) << endl;

/*-------------------------------close the input and the output files----------------------------------*/

fin.close( );

fout.close( );

Page 7: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 331

Example IO2

/**************************************************************************

Program to read an employee’s pay rate and the number of hour of work

And compute his gross pay using file I/O: the name of the input file is

“prog.dat” and the name of the output file is “prog.out”

***************************************************************************/

#include <iostream> // in order to use cout for putput

#include <fstream> // for file I/O

#include <iomanip> // for formatted output

#include <cstdlib> // for exit function

using namespace std;

int main()

{

ifstream finput; // finput is the input stream object

ofstream foutput; // foutput is the output stream object

double payRate; // to hold the pay rate

int hours; // to hold the number of hours

/*---------- connect the I/O stream objects to the files ------------*/

finput.open( “prog.dat” );

if( finput.fail( ) )

{

cerr << endl << “Failure opening input file”;

exit( 1 ); // terminate the program

}

foutput.open( “prog.out” );

if( foutput.fail( ) )

{

cerr << endl << “Failure opening output file”;

exit( 2 ); // terminate the program

}

foutput.setf(ios :: fixed); // for formatted output to the file

foutput.setf(ios :: showpoint); // for formatted output to the file

/*----read the pay rate and the number of hours from the input file---*/

finput >> payRare >> hours;

/*-----compute and print the gross pay into the output file ----------*/

foutput << setprecision(2);

foutput << endl << setw(10) << “Pay Rate:” << setw(6) << payRate;

foutput << endl << setw(10) << “Hours:” << setw(6) << hours;

foutput << endl << setw(10) << “Gross Pay:”

<< setw(6) << (payRate * hours);

finput.close( );

foutput.close( );

return 0;

}

Page 8: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 332

Exercise IO1

The information about a product consists of its ID number, name, unit price, and quantity. Define a

structure named ProductInfo to hold its ID number, name, and price ( price = unit price times quantity)

and then do the following:

1. Define an array productList[ 10 ] of ten ProductInfo structures.

2. Read from the input file, product.data, the ID numbers, names, unit prices, and quantities of these

ten products and build the array productList.

3. Output into the file product.output a table consisting of the products IDs, names, and prices (with

appropriate headings).

Overloading the Stream Insertion Operator << and the Stream

Extraction Operator >>

The stream insertion operator << is a function with two parameters: an object of the class

ostream (on which the output is performed) and the object to be output.

The stream extraction operator >> is a function with two parameters: an object of the class

istream (on which the input is performed) and the object to be input.

Both the stream input and the stream output operators can be implemented as ordinary functions or

as friend functions of the class of the object to be input/output.

Example IO3 Overloading the Insertion and the Extraction Operators as friend Functions

The following class Demo13A is the class Demo13 defined in example M8 with the insertion and the

extraction operators declared as friend functions of the class Demo13A:

class Demo13A

{

public:

Demo13A (int n1 = 0, int n2 = 0); // constructor

int getFirst( ); // returns the value of the first member variable

int getSecond( ); // returns the value of the second member variable

Demo13A operator +( const Demo13A & rightOp );

Demo13A & operator ++( );

friend ostream &operator <<(ostream &outs , const Demo13A &obj);

friend istream &operator >>(istream &ins , Demo13A &obj);

private:

int val1;

int val2;

};

Page 9: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 333

/*----------------------------------------------- operator << -----------------------------------------------------*/

/* Receives an ostream object and a Demo13A object.

Output to the ostream object the values of the member variables of the Demo13A object.

Returns a reference to the ostream object

*/

ostream &operator <<(ostream &outs , const Demo13A &obj)

{

outs << endl << “first value is:\t” << obj.val1

<< endl << “second value is:\t” << obj.val2;

return( outs );

}

/*------------------------------------------------ operator >> ----------------------------------------------------*/

/* Receives an istream object and a reference to a Demo13A object.

Input from the istream object the values for the member variables of the Demo13A object.

Returns a reference to the input stream object

*/

istream &operator >>(istream &ins , Demo13A &obj)

{

ins >> obj.val1 >> obj.val2;

return( ins );

}

/*--------------------------------------- Using the overloaded operators --------------------------------------*/

/* read input from the keyboard and send output to the file prog.out */

#include <fstream>

#include <iostream>

using namespace std;

int main( )

{

ofstream foutput; // foutput is my output stream object

Demo13A tobj, sobj, robj;

foutput.open( “prog.out” );

/*---------------------------read the values for the objects from the keyboard-------------------------*/

cin >> tobj >> sobj;

/*---------------- perform some computations and print the results in the file ----------------------*/

foutput << ++tobj;

robj = ++sobj + Demo13A( 21 , 15 );

foutput << sobj << robj;

foutput.close( );

return 0;

}

Page 10: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 334

Notes

We are able to use the overloaded insertion operator << more than once in a statement (such as

foutput << sobj << robj) because the function (operator <<) returns a reference to the ostream

object which is used again as an operand for the next insertion operator.

Similarly, we are able to use the overloaded extraction operator >> more than once in a statement

(such as cin >> tobj >> sobj) because the function (operator >>) returns a reference to the

istream object which is used again as an operand for the next extraction operator.

Exercise IO2

Create the class Triplet2A by adding to the class Triplet2 that you have defined in exercise M8 the

declarations of the insertion and the extraction operators as friend functions of the class Triplet2A and

then do the following:

A. Write the definitions of the insertion and the extraction operators.

B. Write the definition of function main that does the following:

1. Read values into three objects of the class Trilet2A and initialize the fourth object with (10, 20,

30).

2. Subtract the second object from the first and print the result.

3. Compare the first Triplet2A object to the third and if it is <= to the third output the string “It is

my lucky day”; otherwise, output the string “I will do better next time”.

4. Increment the third object and print the result.

5. Subtract the Triplet2A object (12, 15, 18) from the fourth one (which has been incremented) and

print the result.

Note: Input data are read from the file Triplet2A.dat and the output are written into the file

Triplet2A.output.

Overloading the Insertion and the Extraction Operators as Ordinary

Functions

In order to overload the extraction operator as an ordinary function, you must first define a read

(input) member function of the class with an istream object as argument, and then call that member

function in the definition of the overloaded extraction operator.

In order to overload the insertion operator as an ordinary function, you must first define a print

(output) member function of the class with an ostream object as argument, and then call that member

function in the definition of the overloaded insertion operator.

Example IO4 Overloading the Insertion and the Extraction Operators as ordinary Functions

The following class Demo13B is the class Demo13 (defined in example M8) with two additional

member functions print( ) and a read( ).

Page 11: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 335

class Demo13B

{

public:

Demo13B (int n1 = 0, int n2 = 0); // constructor

int getFirst( ); // returns the value of the first member variable

int getSecond( ); // returns the value of the second member variable

Demo13B operator +( const Demo13B & rightOp );

Demo13B & operator ++( );

void print( ostream &outs ); // outputs the values of the data members

void read( istream &ins ); // reads the values of the data members

private:

int val1;

int val2;

};

/*--------------------------------- Member function print( ) -------------------------------------------*/

/* Receives an ostream object and output the values of the data members to it */

void Demo13B :: print( ostream &outs )

{

outs << endl << “first value is:\t” << val1 << endl << “second value is:\t” << val2;

}

/*------------------------------------- Member function read( ) ----------------------------------------*/

/* Receives an istream object and input from this object the values for the data members */

void Demo13B :: read ( istream &ins )

{

ins >> val1 >> val2;

}

/*---------------------------------------- operator << -----------------------------------------------------*/

/* Receives an ostream object and a Demo13B object.

Output to the ostream object the values of the member variables of the Demo13B object.

Returns a reference to the ostream object

*/

ostream &operator <<(ostream &outs , const Demo13B &obj)

{

obj.print( outs );

return( outs );

}

Page 12: Input / Output in C++ · 2019-05-03 · ©2011 Gilbert Ndjatou Page 325 Input / Output in C++ In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects

©2011 Gilbert Ndjatou Page 336

/*---------------------------------------- operator >> ----------------------------------------------------*/

/* Receives an istream object and a reference to a Demo13B object.

Input from the istream object the values for the member variables of the Demo13B object.

Returns a reference to the istream object

*/

istream &operator >>(istream &ins , Demo13A &obj)

{

obj.read( ins );

return( ins );

}

Exercise IO3

1. Define the class Triplet2B by adding to the class Triplet2 that you have defined in exercise M8 two additional

member functions, void read( istream &ins ) and void print(ostream &outs). Member function read( )

inputs from the object that it receives as argument the values for the data members and print( )

outputs the values of the data members to the object that it receives as argument.

2. Write the definitions of these member functions.

3. Write the definitions of the overloaded insertion and extraction operators as ordinary functions.