You are on page 1of 19

Dept of EEE Object Oriented Programming

STREAM CLASSES

▰ All modern I/O is stream-based.


▰ Stream in C++ means a stream of characters that gets transferred between the program
thread and input or output.
▰ A stream is a connection to a source of data or to a destination for data (sometimes both)
▰ An input stream may be associated with the keyboard
▰ An input stream or an output stream may be associated with a file

Input Stream Output Stream 2

S.Muralidharan 1
Dept of EEE Object Oriented Programming

▰ There are a number of C++ stream classes eligible and defined which is related to the files and streams
for providing input-output operations.
▰ All these classes are defined in the file iostream.h. Figure given below shows the hierarchy of these
classes.
▰ It is perfectly valid to use the same I/O statements in C++ as in C -- The very same printf, scanf, and
other stdio.h functions that have been used until now.

▰ However, C++ provides an alternative with the new stream input/output features. The header file is
named iostream and the stream I/O capabilities are accessible when you use the pre-processor
declaration:
#include <iostream> // No “.h” on std headers
using namespace std; // To avoid things like
// std::cout and std::cin

▰ Several new I/O objects available when you include the iostream header file. Two important
ones are:
▻ cin // Used for keyboard input (std::cin)
▻ cout // Used for screen output (std::cout)
▰ Both cin and cout can be combined with other member functions for a wide variety of
special I/O capabilities in program applications.
▰ Since cin and cout are C++ objects, they are somewhat "intelligent":
▻ They do not require the usual format strings and conversion specifications.
▻ They do automatically know what data types are involved.
▻ They do not need the address operator, &.
▻ They do require the use of the stream extraction ( >> ) and insertion ( << ) operators.
4

S.Muralidharan 2
Dept of EEE Object Oriented Programming

HIERARCHY OF STREAM CLASS

▰ ios class is topmost class in the stream classes hierarchy. It is the base class for istream, ostream, and
streambuf class.
▰ istream and ostream serves the base classes for iostream class. The class istream is used for input
and ostream for the output.
▰ Class ios is indirectly inherited to iostream class using istream and ostream. To avoid the duplicity of
data and member functions of ios class, it is declared as virtual base class when inheriting in istream
and ostream. 5

▰ ios class − This class is the base class for all stream classes. The streams can be input or output
streams. This class defines members that are independent of how the templates of the class are defined.
▰ istream Class − The istream class handles the input stream in c++ programming language. These input
stream objects are used to read and interpret the input as a sequence of characters. The cin handles the
input. It also provides number of function for handling chars, strings and objects such as get, getline,
read, ignore, putback etc.
▰ ostream class − The ostream class handles the output stream in c++ programming language. These
output stream objects are used to write data as a sequence of characters on the screen. cout and puts
handle the out streams in c++ programming language. It provides number of function for handling chars,
strings and objects such as write, put etc..
▰ The iostream -This class is responsible for handling both input and output stream as both istream
class and ostream class is inherited into it. It provides function of both istream class and ostream class
for handling chars, strings and objects such as get, getline, read, ignore, putback, put, write etc..
6

S.Muralidharan 3
Dept of EEE Object Oriented Programming

EXAMPLE FOR OUT STREAM

OUT STREAM
COUT

#include <iostream>
using namespace std;
int main()
{
cout<<"This output is printed on screen";
}

Output
This output is printed on screen

PUTS
#include <iostream>
using namespace std;
int main()
{
puts("This output is printed using puts");
}

Output
This output is printed using puts 9

S.Muralidharan 4
Dept of EEE Object Oriented Programming

EXAMPLE FOR IN STREAM

IN STREAM
CIN GETS
#include <iostream>
#include <iostream> using namespace std;
using namespace std; int main()
int main() { char ch[10];
{ int no; puts("Enter a character array");
cout<<"Enter a number "; gets(ch);
cin>>no; puts("The character array entered using gets is : ");
cout<<"Number entered using cin is "<< no puts(ch);
} }
Output
Enter a number 3453 Output
Number entered using cin is 3453 Enter a character array
thdgf
The character array entered using gets is :
thdgf

10

Use of >> and << operators

▰ Formatted output is carried out on streams via the stream insertion << and stream
extraction >> operators. For example,
cout << value;
cin >> variable;
▰ Take note that cin/cout shall be the left operand and the data flow in the direction of the arrows.
▰ The << and >> operators are overloaded to handle fundamental types (such as int and double),
and classes (such as string). You can also overload these operators for your own user-defined
types.
▰ The cin << and cout >> return a reference to cin and cout, and thus, support cascading
operations. For example,
cout << value1 << value2 << .... ;
cin >> variable1 << variable2 << .... ;
▰ Spaces , Newline and tabs are skipped while using Cin . The reading for a variable will be
terminated at the encounter of a white space or a character that doesnot match the destination
11
data type.

S.Muralidharan 5
Dept of EEE Object Oriented Programming

OVERLOADING OF >> AND << OPERATOR


▰ In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
We must know the following things before we start overloading these operators.
1) cout is an object of ostream class and cin is an object of istream class
2) These operators must be overloaded as a global function. And if we want to allow them to access
private data members of the class, we must make them friend.
▰ In operator overloading, if an operator is overloaded as a member, then it must be a member of the
object on the left side of the operator. For example, consider the statement “ob1 + ob2” (let ob1 and
ob2 be objects of two different classes). To make this statement compile, we must overload ‘+’ in a
class of ‘ob1’ or make ‘+’ a global function.
▰ The operators ‘<<‘ and ‘>>’ are called like ‘cout << ob1’ and ‘cin >> ob1’. So if we want to make them a
member method, then they must be made members of ostream and istream classes, which is not a
good option most of the time. Therefore, these operators are overloaded as global functions with two
parameters, cout and object of user-defined class.
12

▰ istream_withassign class: This class is variant of istream that allows object assignment. The
predefined object cin is an object of this class and thus may be reassigned at run time to a
different istream object.

13

S.Muralidharan 6
Dept of EEE Object Oriented Programming

class demo {
public:
int dx, dy;
// operator overloading using friend function
friend void operator>>(demo& d, istream& mycin)
{
// cin assigned to another object mycin
mycin >> d.dx >> d.dy;
}
};
Input
int main() 45
{
demo d; Output
cout << "Enter two numbers dx and dy\n"; Enter two numbers dx and dy
// calls operator >> function and 45
// pass d and cin as reference dx = 4 dy = 5
d >> cin; // can also be written as operator >> (d, cin) ;
cout << "dx = " << d.dx << "\tdy = " << d.dy;
}
14

▰ ostream_withassign class: This class is variant of ostream that allows object assignment.
The predefined objects cout, cerr, clog are objects of this class and thus may be reassigned
at run time to a different ostream object. Example:To show that cout is object of ostream
class.

15

S.Muralidharan 7
Dept of EEE Object Oriented Programming

#include <iostream>
class demo {
public:
int dx, dy;
demo()
{
dx = 4;
dy = 5;
}
// operator overloading using friend function
friend void operator<<(demo& d, ostream& mycout)
{
// cout assigned to another object mycout
mycout << "Value of dx and dy are \n"; Output
mycout << d.dx << " " << d.dy; The value of dx and dy are
} 45
};
int main()
{
demo d; // default constructor is called
// calls operator << function and
// pass d and cout as reference
d << cout; // can also be written as operator << (d, cout) ; 16
}

OVERLOADING OF >> AND << OPERATOR


#include <iostream> int main()
using namespace std; { Distance D1(11, 10), D2(5, 11), D3;
class Distance { cout << "Enter the value of object : " << endl;
private: int feet; // 0 to infinite cin >> D3;
int inches; // 0 to 12 cout << "First Distance : " << D1 << endl;
public: // required constructors cout << "Second Distance :" << D2 << endl;
Distance() { cout << "Third Distance :" << D3 << endl;
feet = 0; return 0;
inches = 0; } }
Distance(int f, int i) {
feet = f;
inches = i; }
friend ostream &operator<<( ostream &output, const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches; $./a.out
return output; Enter the value of object :
} 70
friend istream &operator>>( istream &input, Distance &D ) 10
{ First Distance : F : 11 I : 10
input >> D.feet >> D.inches; Second Distance :F : 5 I : 11
return input; Third Distance :F : 70 I : 10
} 17
};

S.Muralidharan 8
Dept of EEE Object Oriented Programming

Formatted and Unformatted input/output

▰ The ostream class is a typedef to basic_ostream<char>. It contains two set of output


functions: formatted output and unformatted output.
▻ The formatted output functions (via overloaded stream insertion operator <<) convert numeric
values (such as int, double) from their internal representations (e.g., 16-/32-bit int, 64-bit double) to
a stream of characters that representing the numeric values in text form.
▻ The unformatted output functions (e.g., put(), write()) outputs the bytes as they are, without format
conversion.
▰ Formatting Output via the Overloaded Stream Insertion << Operator
▻ The ostream class overloads the stream insertion << operator for each of the C++ fundamental
types (char, unsigned char, signed char, short, unsigned short, int, unsigned int, long, unsigned
long, long long (C++11), unsigned long long (C++11), float, double and long double. It converts a
numeric value from its internal representation to the text form.
ostream & operator<< (type) // type of int, double etc
▻ The << operator returns a reference to the invoking ostream object. Hence, you can
18
concatenate << operations, e.g., cout << 123 << 1.13 << endl;.

Formatted and Unformatted input/output

▰ Formatting Input via the Overloaded Stream Extraction >> Operator


▻ Similar to the ostream class, the istream class is a typedef to basic_istream<char>. It also
supports formatted input and unformatted input. In formatting input, via overloading
the >> extraction operator, it converts the text form (a stream of character) into internal
representation (such as 16-/32-bit int, 64-byte double).
istream & operator<< (type &) // type of int, double etc.

▻ The >> operator returns a reference to the invokind istream object. Hence, you can
concatenate >> operations, e.g., cin >> number1 << number2 <<....

19

S.Muralidharan 9
Dept of EEE Object Oriented Programming

Unformatted input/output

▰ The classes istream and ostream define two member functions get() and put() respectively
to handle the single character input/output operations.
▰ In unformatting input, such as get(), getlin(), read(), it reads the characters as they are,
without conversion.
▰ There are two types of get() functions.
▻ get(char*) and get(void) prototypes to fetch a character including the blank space, tab and
newline character.
▻ The get(char*) version assign the input character to its argument and the get(void) version
returns the input character.

20

Unformatted input/output

▰ This code reads and displays a line of text(terminated by a newline character). Remember
the operator >> can also be used to read a character but it will skip the white spaces and
newline character. The above while loop will not work properly if the statement “cin>>c” is
used in place of “cin.get(c)”.
▰ The get(void) version is used as follows. The value returned by the function get() is assigned
to the variable c.

21

S.Muralidharan 10
Dept of EEE Object Oriented Programming

▰ The ostream's member function put() can be used to put out a line of text, character by
character.
▻ put() returns the invoking ostream reference, and thus, can be cascaded.
▰ The below line displays a character ‘x’.

▰ The below line displays the value of variable ‘ch’ provided the variable ‘ch’ must contain a
character value.

▰ Even a number as an assignment could also be used with put(). In the below it displays a
character ‘D’ which corresponds to the ASCII value 68.

22

▰ The below program reads the character and displays it.

23

S.Muralidharan 11
Dept of EEE Object Oriented Programming

Example program

24

getline() and write()

▰ We can read and display a line of text more efficiently using line oriented input/output
functions getline() and write().
▰ The getline() function reads a whole line of text that ends with a newline character(RETURN
key). This can be invoked using the object cin.

▻ In this either a newline character or a line of size (size-1) will cease the input operation(whichever
occurs first). Newline character is received but not saved.
▻ Sample

▻ In the above either a line terminated with newline character but of size less than 20 is accepted or
if the size exceeds , only first 19 characters including white space is received.
25

S.Muralidharan 12
Dept of EEE Object Oriented Programming

getline() and write() : Example program

26

getline() and write()

▰ The write() function displays an entire line and its format is

▻ The first argument represent the name of the string to be displayed and the second argument size
indicates the number of characters to display. Note that it does not stop displaying the characters
automatically when the null character is encountered. If the size is greater than the length of line,
then it displays beyond the bounds of line.

27

S.Muralidharan 13
Dept of EEE Object Oriented Programming

▻ Output

Note
=

28

Formatted Console I/O Operations

▰ C++ supports provision for formatting the output. These features include :
▻ ios class functions and flags
▻ Manipulators
▻ User-defined output functions.

▰ ios member functions include

29

S.Muralidharan 14
Dept of EEE Object Oriented Programming

▰ Manipulators are special functions that can be included in the I/O statements to alter the
format parameters of a stream. To access these manipulators, the file “iomanip” should be
included in the program. Manipulators include :

▰ In addition to these functions supported via C++ library, we can create out own manipulator
functions to provide any special output formats.

30

Example program with “width()” ios function


Format

Output

31

S.Muralidharan 15
Dept of EEE Object Oriented Programming

Example program with “precision()” ios function


Format

Output

32

Example program with “fill()” ios function


Format

Output

33

S.Muralidharan 16
Dept of EEE Object Oriented Programming

Formatting Flags, Bit-fields and setf()

▰ setf(): The setf method is used to set various flags for formatting output.Format flags (bits
of format flag variable) can be set using setf() function in two forms as follows:
▻ fmtflags ios::setf (ios::fmtflags flg)
▻ fmtflags ios::setf (ios::fmtflags flg, ios::fmtflags mask)
▰ To set multiple flags, use OR (|) operator to combine them (for example, ios::fixed |
ios_base::uppercase )

▰ unsetf(): The unsetf method is used To remove the flag setting

34

Flags and bit-fields for setf() function

Sample 1 Sample 2

35

S.Muralidharan 17
Dept of EEE Object Oriented Programming

Sample 3 – Displaying trailing zeros and plus sign


“showpoint” and “showpos” do not have any bit fields
and therefore are used as single argument in ‘setf()’
This is because setf function is a overloaded function
in ios. Some of such cases are listed below :

36

Output

37

S.Muralidharan 18
Dept of EEE Object Oriented Programming

Defining our own manipulators


▰ C++ provides many predefined manipulators but you can also
create your own manipulators. The syntax for creating user
defined manipulators is defined as follows:

38

S.Muralidharan 19

You might also like