0% found this document useful (0 votes)
5 views6 pages

C++ Stream Classes and I/O Operations

The document explains input and output operations in C++, detailing the concept of streams, their hierarchy, and predefined streams like cin and cout. It covers unformatted and formatted I/O operations, including the use of overloaded operators, member functions, manipulators, and user-defined output functions for formatting. The document provides examples to illustrate the usage of these features in C++ programming.

Uploaded by

Rayudu Manikonda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

C++ Stream Classes and I/O Operations

The document explains input and output operations in C++, detailing the concept of streams, their hierarchy, and predefined streams like cin and cout. It covers unformatted and formatted I/O operations, including the use of overloaded operators, member functions, manipulators, and user-defined output functions for formatting. The document provides examples to illustrate the usage of these features in C++ programming.

Uploaded by

Rayudu Manikonda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INPUT AND OUTPUT IN C++

1. What a stream? Explain the hierarchy of stream classes in C++.


Ans: A stream is a general name given to a flow of data. Different streams are used to
represent different kinds of data flow. Each stream is associated with a particular class, which
contains member functions and definitions for dealing with that particular kind of data flow.
A stream is sequence of bytes. It acts either as a source from which the input data can
be obtained or as a destination to which the output data can be sent. The source stream that
provides data to the program is called the input stream and the destination stream that
receives the output from the program is called the output stream.

Input stream
Input
device Extraction
From input
stream

Program
Output stream insertion
Output Into output
device Stream

The data in the input stream can come from the keyboard or any other storage device.
Similarly, the data in the output stream can go to the screen or nay other storage device.
Hence a stream acts as an interface between the program and input/ output device.
Pre defined streams
C++ contains several predefined streams that are automatically opened when a
program begins its execution. They are
a) cin : cin represents the input stream connected to the standard input device(usually
the keyboard)
b) cout : cout represent the output stream connected to the standard output device
(usually the screen).
c) cerr : cerr represent the error stream connected to the standard error device
(usually the screen).
d) clog : A fully buffered version of cerr. It controls error messages that are passed
from buffer to the standard error device.

Hierarchy of C++ stream classes :


The C++ I/O system contains a hierarchy of classes that are used to define various
streams to deal with both the console and disk files. These classes are called stream classes.
The following figure shows the hierarchy of stream classes used for I/O operations with the
console unit. These classes are declared in the header file <iostream.h>

ios

istream ostream streambuffer

iostream filebuffer

istream_withassign iostream_withassign ostream_withassign


Stream classes for console operations

Class name Contents

ios(General input/output stream Contains basic facilities that are used by all other input
class) and output classes

Also contains a pointer to buffer object(streambuf


object)

Declares constants and functions that are necessary for


handling formatted input and output operations

istream(input stream) Inherits the properties of ios

Declares input functions such as get(),getline() and


read()

Contains overloaded extraction operator>>

ostream(output stream) Inherits the property of ios

Declares output functions put() and write()

Contains overloaded insertion operator <<

iostream (input/output stream) Inherits the properties of istream and ostream through
multiple inheritance and thus contains all the input and
output functions

streanbuf Provides an interface to physical devices through buffer

Acts as a base for filebuf class used ios files

2. Explain the different unformatted I/O operations?


Ans:
Overloaded operators: >> and <<
The >> (extraction operator) operator is overloaded in the istream class and <<
(insertion operator) operator is overloaded in the ostream class.
cin and cout are the predefined stream objects for the input and output of data of
various types.
The general format for reading the data from the keyboard:
cin >> variable1 >> variable2 ……… >> variableN
The general format for displaying data on the screen is:
cout << variable1 << variable2 ………… << variableN
here,variable1, variable2 ……… are valid c++ variable names that have been declared
already.
Ex:
#include <iostream.h>
{
int x;
float y;
char ch;
cin>>x>>y>>ch;
cout<<”X”<<x<<”\nY:”<<y<<\nCharacter:”<<ch;
}
put( ) and get( ) functions:
The classes istream and ostream defines two member functions get( ) and put( )
respectively to handle single character I/O operations.
General syntax:
void get(char*);
char get( );
void put(char);
Ex:
// This program reads a line of text and displays using get() and put() functions
#include <iostream.h>
void main()
{
char ch;
ch=[Link]();
while(ch !='\n')
{
[Link](ch);
ch=[Link]();
}
}
getline( ) and write( ) functions :
we can read and display a line of text more efficiently using the line oriented I/O
functions getline( ) and write( ).
Genral syntax :
[Link](line,size);
[Link](line,size);
The getline( ) function reads a whole line of text that ends with a new line character. This
function should be invoked by using the object cin. This function reads character input into
the variable line. The reading is terminated as soon as either the new line character ‘\n’ is
encountered or size-1 characters are read(whichever occurs first).
The write( ) function displays an entire line. The first argument line represents the name
of the string to be displayed and the second argument size indicates the number of characters
to display.
Ex: // Example program on getline() and write()
#include <iostream.h>
void main()
{
char str[20];
cout<<"Enetr a string\n";
[Link](str,20);
for(int i=0;str[i] !='\0';i++)
{
[Link](str,i+1);
cout<<"\n";
}
}
3. Explain different formatted console I/O operations?
Ans :
C++ supports a number of features that could be used for formatting the output. These
features include:
 ios class functions and flags
 Manipulators
 User defined output functions
ios class functions and flags:
The ios class contains a large number of member functions that would help us to
format the output in a number of ways. The most important once among them are listed in the
following table:
Function Task
width ( ) To specify the required field size for displaying an output value
Precision( ) To specify the number of digits to be displayed after the decimal point of a float
value
fill( ) To specify a character that is used to fill the unused portion of a field
setf( ) To specify format flags that can control the form of output display (such as left-
justification and right justification)
unsetf ( ) To clear the flags specified

The following table represents the flags and bit fields defined in ios class :
Format required Flag (arg1) Bit-field(arg2)
Left-justified output ios :: left ios :: adjustified
Right justified output ios :: right ios :: adjustified
Padding after sign or base ios :: internal ios :: adjustified
Indicator (like +##20)
Scientific notation ios :: scientific ios :: floatfield
Fixed point notation ios :: fixed ios :: floatfield
Decimal base ios :: doc ios :: basefield
Octal base ios :: oct ios :: basefield
Hexadecimal base ios :: hex ios :: basefield

Table flags that do not have bit fields:


Flag Meaning
ios :: showbase Use base indicator on output
ios :: showpos Print + before positive numbers
ios :: showpoint Show trailing decimal point and zeros
ios :: uppercase Use upper case letters for hex output
ios :: skipus Skip white space on input
ios :: unitbuf Flush all streams after insertion
ios :: stdio Flush stdout and stderr after insertion

Ex: // Example program on ios class functions and flags


#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
[Link]('*'); // fill the unused portion with *
[Link](2); // display two digits after decimal point
[Link](ios::showpoint);// to display trailing zeros
for(int i=1;i<=5;i++)
{
[Link](5); // sets the field with to 5 to display i
cout<<i;
[Link](10); //sets the field width to 10
cout<<1.0/i<<"\n";
}
}

Manipulators :
Manipulators are special functions that can be included in the I/O statements to alter
the format parameter of a stream. The following table shows some important manipulator
functions that are frequently used. To access these manipulators the file iomanip should be
included in the program.
Manipulators Meaning Equivalent
setw(int w) Set the field width to w. width( )
setprecision(int d) Set the floating point precision to d. precision( )
setfill(int c) Set the fill character to c. setf( )
setiosflags(long f) Set the format flag f. setf( )
Resetiosflags(long f) Clear the flag specified by f unsetf( )
Endif Insert new line and flush stream “\n”
Ex: // Example program on manipulators
#include <iostream.h>
#include <iomanip.h>
void main()
{
for(int i=1;i<=5;i++)
{
cout<<setw(5)<<setfill('*')<<i;
cout<<setprecision(2)<<setw(10)<<setiosflags(ios::showpoint)<<1.0/i<<"\n";
}
}
User defined output functions:
We can design our own manipulators for certain special purposes. The general form
for creating a manipulator is
ostream & manipulator(ostream & output)
{
……..
…….. (code)
……..
return output;
}
Here, the manipulator is the name of the manipulator under creation. The following
function defines a manipulator called unit that displays “inches”:
ostream & unit(ostream & output)
{
output << “inches”;
return output;
}
The statement
cout << 36 < unit;
will produce the following output 36 inches
we can also create manipulators that could represent a sequence of operations.
Ex:
ostream & show (ostream & output)
{
[Link](ios::showpoint);
[Link](ios::showpos);
output << setw(10);
return output;
}
This function defines a manipulator called show that turns on the flags showpoint and
showpos declared in the class ios and sets the field width to 10.
Example program on user-defined manipulator :
// a program to create and use user-defined manipulator
#include <iostream.h>
#include <conio.h>
ostream & mymanip(ostream & output)
{
[Link](10);
[Link](ios::right,ios::adjustfield);
[Link](2);
[Link]('*');
[Link](ios::showpoint);
return(output);
}
void main()
{
clrscr();
cout<<mymanip<<10/3.0;
}

You might also like