0% found this document useful (0 votes)
61 views19 pages

Module - 36 C++ I/O System Basics

This document provides an overview of C++ input/output (I/O) streams. It discusses the stream classes used for I/O like istream, ostream, and iostream. It describes the predefined standard input stream cin and standard output stream cout. Functions of the istream and ostream classes are covered for reading input and writing output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views19 pages

Module - 36 C++ I/O System Basics

This document provides an overview of C++ input/output (I/O) streams. It discusses the stream classes used for I/O like istream, ostream, and iostream. It describes the predefined standard input stream cin and standard output stream cout. Functions of the istream and ostream classes are covered for reading input and writing output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1

Module - 36

C++ I/O System Basics


Table of Contents

1. Introduction
2. Stream classes of C++
3. Predefined Standard Input/Output Streams
4. Functions of <istream> class
5. Functions of <ostream> class
6. Summary

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
2

Learning outcome –
After studying this module, you will be able to:
1. Learn about Stream classes of C++
2. Know about Predefined Standard Input/Output Streams
3. Study about Functions of <istream> class
4. Study about Functions of <ostream> class

1. Introduction
In C++, the Input/output is offered as a component of the standard library. The C++ standard
libraries present widespread set of input/output facilities which are most commonly used for I/O
operations. The Input/output in C++ language mostly occurs in streams, which are nothing but
sequences of bytes. In general, the streams perform two types of operations, they are Input
operation and Output operation.

2. Stream classes of C++


C++ includes a hierarchy of classes called as Stream classes that are mainly used to describe
various streams to deal with console and disk files. The stream classes are stated in the iostream
or iostream.h header file. The stream classes of C++ are:

ios

INPUT POINTER OUTPUT

istream streambuf ostream

iostream

istream_withassign iostream_withassign ostream_withassign

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
3

From the above figure:


 It is clear that ios is the base class for the istream, i.e., Input stream and base class for
ostream, i.e., Output stream.

 The istream and ostream classes are in turn base classes for the class iostream, i.e.,
Input/Output Stream.

The stream classes and their functionality can be represented in the table as follows:

Stream class Functionality and their Description


ios class It offers the basic services that are used by all input and output classes. In
addition, it provides a pointer to a buffer object, i.e., streambuf object.
istream class It tries to inherit the properties from the base class ios. It offers the services for
input methods. In the usual manner, it provides a mechanism to accept
the data from the input device. It declare the input functions such as get(),
getline(), read() and it also include overloaded extraction operator (>>).
ostream class It tries to inherit the properties from the base class ios. It offers the services for
output methods. In the usual manner, it provides a mechanism to displa y the
data to the output device. It declare the output functions such as put(), write()
and it also include overloaded insertion operator (<<).
streambuf class It tries to provide memory for a buffer. It also provides the methods of the
class for loading the contents of the buffer, access the contents of the buffer,
flush the contents of the buffer, organizing the memory of the buffer. It also
holds the mainly important and primitive functions for the streams on a First-
In-First-Out Order basis.
_withassign C++ language consists of 3 _withassign classes, they are istream_withassign,
classes ostream_withassign and iostream_withassign. The istream_withassign is a
derived class which is derived from base class istream class. The
ostreamwithassign is a derived class which is derived from base class ostream
class. The iostreamwithassign is a derived class which is derived from base
class iostream class. The _withassign classes basically consist of assignment
operators. By using the assignment operators, it is possible to copy the objects
of the _withassign classes. By making the assignment operators as private, the
copying on istream, ostream and iostream classes can be stopped.
filebuf class It is a derived class which is inherited from the base class streambuf. It tries to
present the necessary and basic operations that are related to files.
strstreambuf It is a derived class which is inherited from the base class streambuf. It is
class mainly designed to hold the buffers that are related to memory.

3. Predefined Standard Input/Output Streams


C++ language consists of four streams that are mainly defined for standard Input/Output. The
two operators, i.e., extraction operator (>>) and insertion operator (<<) are overloaded and are
defined on basic or primary data types. It is also possible to overload the extraction and insertion
operators on the user-defined datatypes, but it can be possible for specific objects of the class.

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
4

The four streams are:


 cin: It is mainly used to get the input from standard input device, such as keyboard.
 cout: It is mainly used to display the output to standard output device, such as monitor or
screen.
 cerr: It is mainly used for standard error to display on monitor or screen.
 clog: It is mainly used for buffered error to display on monitor.

3.1 Standard Input Stream (cin)


The istream class supports the methods for input of formatted data as well as unformatted data.
The cin object of istream class along with extraction operator ( >>) is mainly used for the input
of primary types. It is possible with the cin object to overload the extraction operator (>>) for the
user defined types, but it can be used for the class of input object. In general, the operator (>>) is
basically, the bitwise right shift operator which is overloaded to do the process of extraction
operation. Since, after each and every extraction operation, the extraction operator tries to send a
reference back to cin, therefore, it allows cascading operation and it is possible to extract a
quantity of values written one after another and each of them lead by extraction operator.

Syntax:
cin >> variable1 >> varibale2 ... >> variableN;

In the above syntax:


The variable1, variable2, …, variableN are valid C++ variable names.

Example:
cin>>rollno>>name>>total;

Program to illustrate the usage of cin object and extraction operator (>>)

#include<iostream>
using namespace std;
int main()
{
int number1 ;
double number2 ;
char ch1 ;
char Grade [30];
cout <<"Enter value of Number1 : " ; cin >>number1;
cout <<"Enter the value of Number2 : "; cin >>number2;
cout <<"Enter the value of ch1 : "; cin>>ch1 ;
cout<<"Enter a Grade : "; cin >> Grade ;
cout <<"The data that is entered is "<<endl;
cout <<"Number1 = "<<number1 <<" , Number2 = "<<number2 <<" , ch1 = "<<ch1
<<", Grade = " <<Grade <<endl;
}

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
5

When the above code is compiled and executed, it produces the following result:
Enter value of Number1 : 10
Enter the value of Number2 : -20
Enter the value of ch1 : Z
Enter a Grade : Excellent
The data that is entered is
Number1 = 10 , Number2 = -20 , ch1 = Z , Grade = Excellent

3.2 Standard Output Stream


The cout object of ostream class is used for standard output along with overloaded insertion
operator (<<). To do the process of insertion operation of basic data type, the operator <<, i.e.,
bitwise left shift binary operator is overloaded. The cout object can be used for user defined data,
but it is must that the overloading functions for operator << are to be described by the
programmer for the class of the objects being that are dealt with. Since, after each and every
insertion operation, the insertion operator tries to return the value of reference to the object of
ostream class, i.e., cout, therefore, it allows the cascading of stream objects which helps to write
a number of outputs in the same output statement.

Syntax:
cout << item1 << item2 << … << itemN;

In the above syntax:


The item1, item2, …,itemN can be variables of fundamental data type or constants of
fundamental data type.

Example:
cout<<Nameofcustomer<<" paid rupees "<<Price<<" for "<< Custno <<" Mangoes "
<<endl;

Program to illustrate the use of cout object and insertion operator (<<)

#include<iostream>
using namespace std;
int main()
{
int Custno =401;
double Price =1000.5;
char flag = 'F';
char Nameofcustomer[] = "Deepali";
cout << "flag is "<<flag<<endl;
cout<<Nameofcustomer<<" paid rupees "<<Price<<" for "<< Custno <<" Mangoes "
<<endl;
}
When the above code is compiled and executed, it produces the following result:
flag is F
Deepali paid rupees 1000.5 for 401 Mangoes
C and C++ Programming
Electronic Science
36. C++ I/O System Basics
6

3.3 Standard Error Stream (cerr)


The cerr, which is a predefined object is an instance of ostream class that corresponds to the
standard error stream. It is related with the cstdio stream stderr. The cerr object is said to be
“connected” to the standard error device, which is a display screen or monitor, but, since, the cerr
object is un-buffered, therefore, each stream insertion to cerr causes its output to come into view
instantly. The cerr object can also be used in combination with the stream insertion operator.
By default, most of the systems have their regular error output which is set to the console, where
the text messages are displayed, even though this can normally be forwarded. Because cerr is an
predefined object of ostream class, it is possible to write the characters to it either as formatted
data with the help of the insertion operator (<<) or as unformatted data with the help of the
write member function.

Program to illustrate the usage of standard error stream (cerr)

#include <iostream >


using namespace std;
int main( )
{
char text[] = "Unable to read the content";
cerr << "Error message : " << text << endl;
}

When the above code is compiled and executed, it produces the following result:

Error message : Unable to read the content

3.4 clog
The clog which is a predefined object is an instance of ostream class which represents the
standard logging stream. The clog object is said to be connected to the standard error device,
which is a display screen, but because, the predefined object clog is buffered, therefore, each
insertion to clog might effects its output to be seized in a buffer until the buffer is full or until the
buffer is flushed. The clog object can also be used in combination with the stream insertion
operator. It is linked with the cstdio stream stderr, like cerr. By default, the majority of the
systems have their normal error and logging output which is mostly going to the console, where
the text messages are displayed, even though this can usually be forwarded. Since, clog is a
predefined object of ostream class , it is possible to write characters to it either as formatted data
with the help of the insertion operator (<<) or as unformatted data with the help of the
write member function.

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
7

Program to demonstrate the usage of cerr and clog objects

#include <iostream>
using namespace std;

void test( )
{
int n = 0;
cout << "Enter a number: "<<endl;
cin >>n;
cerr << "test for cerr" << endl;
clog << "test for clog" << endl;
}
int main( )
{
int i = 0;
cout << "Enter a number: "<<endl;
cin >> i;
cerr << "test for cerr" << endl;
clog << "test for clog" << endl;
test( );
}
When the above code is compiled and executed, it produces the following result:

Enter a number: 3
test for cerr
test for clog

Enter a number: 2
test for cerr
test for clog

Program to implement the usage of cerr and clog objects

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number ;
cout<<"Enter a number : "; cin>>number;
if (number<0)
{
cout<<"The value is negative\n"<<endl;
C and C++ Programming
Electronic Science
36. C++ I/O System Basics
8

cout<< "Enter a positive number \n";


exit(0);
}
cout<<"Square root of number"<<number<<" is "<<sqrt(number)<<endl;
cerr<<"Square root of 35 is "<<sqrt(35)<<endl;
clog << "The square root of 25 is : "<<sqrt(25)<<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Enter a number : 36
Square root of number 36 is 6
Square root of 35 is 5.91608
The square root of 25 is : 5

Enter a double number: -25


The value is negative
Enter a positive number

Program to illustrate the usage of clog object

#include <iostream>
using namespace std;
class Test
{
int number;
Test()
{
clog << "static constructor\n";
}
~Test()
{
clog << "static destructor\n";
}
};
Test t1; // static object
int main()
{
clog << "main function\n";
}

When the above code is compiled and executed, it produces the following result:

static constructor
main function
C and C++ Programming
Electronic Science
36. C++ I/O System Basics
9

static destructor

3.5 Functions of <istream> class


Some of the most commonly used functions of <istream> class are get(), getline(), ignore(),
peek(), putback() and gcount().

a) get()
The get() function is a member function of istream class is mainly used to read a single character
from an input device. The different ways of using get() function are:

 get() function with no arguments


 get() function with a character argument
 get() function with two arguments
 get() function with three arguments

 get() function with no argume nts


The get() function with no arguments tries to enter one character from the selected streams
including whitespace and it tries to return the character as the value of the function call.
When End-Of-File on the stream is encountered, it tries to return EOF.

Example:
cin.get();
char ch1;
ch1=cin.get()

Program to implement the usage of get() function with no arguments

#include<iostream>
using namespace std;
int main ()
{
char ch1;
cout <<"Enter a character : ";
ch1 = cin.get();
cout <<"The character that is entered is = "<< ch1<< endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Enter a character : Z
The character that is entered is = Z

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
10

 get() function with a character argument


The get() function with a character argument tries to enter the next character from the input
stream including whitespace. When End-Of-File (eof) on the stream is encountered, it tries
to return false. It tries to returns a reference to the object of istream class for which the get()
member function is being invoked.

Example:
char ch1;
cin.get(ch1);

Program to implement the use of get() function with a character argument

#include<iostream>
using namespace std;
int main()
{
char ch1;
cout <<"Enter a character : ";
cin.get(ch1);
cout <<"The Character that is entered is "<< ch1;
cout<<"\n";
return 0;
}

When the above code is compiled and executed, it produces the following result:

Enter a character : Z
The character that is entered is = Z

 get() function with two argume nts


The get() function with two arguments tries to read first n-1 characters one after another into
the buffer. The last character is the NULL( \0) character which indicates the end of string and
gets attached by the system.

Syntax:
cin.get(char*buffer, size_t n);

Example:
char Name[20];
cin.get(Name,6);

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
11

Program to implement the usage of get() function with two arguments


#include <iostream>
using namespace std;
int main()
{
int n =0;
char Name[20];
cout<<"Enter a name : " ;
cin.get (Name,6);
cout <<"Name that is entered is ; "<< Name <<endl;
}
When the above code is compiled and executed, it produces the following result:
Enter a name : Sherlock
Name that is entered is Sherl

 get() function with three arguments


Syntax:
cin.get( char* buffer, size_t n, char delimeter)

In the above syntax:


The (n – 1) is the highest number of characters that may be read. It also consist of a
delimiting character, i.e. char delim. If the delimiter character is met, then the function stops
reading the further characters, even though the number (n – 1) is not reached.

Example:
char Buffer [ ]= "Example of getline function in CPP";
char ch1=‘#’;
cin.getline( Buffer, 15,ch1);

Program to implement the usage of get() function with three arguments


#include <iostream>
using namespace std;
int main()
{
char ch1 = '#'; // # is a delimiting character
char Text1[30];
cout<<"\nEnter a Text1 : " ;
cin.get (Text1,20, ch1 );
cout <<"The text that is written is : "<< Text1 <<endl;
}

When the above code is compiled and executed, it produces the following result:
Enter a Text1 : this is my first program in cpp on i/o #basics
C and C++ Programming
Electronic Science
36. C++ I/O System Basics
12

The text that is written is : this is my first pr

b) getline()
The getline() function works like that of get() function, i.e., it tries to add a null character after
the line in the character array. It eliminates the delimiter from the stream, but it does not store it
in the character array. It is must that the getline() function has to be used with object of istream
class and it is mainly useful to read a complete line. The getline() function can have two or three
arguments.
Syntax:
getline (char* s, streamsize n );
getline (char* s, streamsize n, char delimeter);

Example:
char Buffer [ ]= "Example of getline function in CPP";
char ch1=‘#’;
cin.getline( Buffer, 20);
cin.getline( Buffer, 15,ch1);

Program to implement the usage of getline() function


#include <iostream>
using namespace std;
int main()
{
char Text[50] ;
cout << "Enter Text : ";
cin.getline(Text,30);
cout<<"Text that is entered is : ";
cout<<Text;
}
When the above code is compiled and executed, it produces the following result:
Enter Text : Hello World
Text that is entered is : Hello World

c) ignore()
The ignore() function reads and it tries to rejects up to n characters or up to the reading of
delimiter character or end of file whichever occurs first. The default value of n is 1.

Syntax:
cin.ignore (streamsize n, int delimiter)

Program to implement the usage of ignore() function


#include <iostream>
using namespace std;
int main ()
C and C++ Programming
Electronic Science
36. C++ I/O System Basics
13

{
char firstname, lastname;
cout<<"Enter first name and last name: ";
firstname = cin.get();
cin.ignore(30,' ');
lastname = cin.get();
cout<<"The initial letters are: "<<firstname<<lastname<<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Enter first name and last name: Vivian Richards
The initial letters are: VR

d) peek()
The peek() function returns the next character from an input stream, but it does not take out the
character from the stream.

Example:
cin.peek('H');

e) putback()
The putback() function tries to return the formerly read character to the input stream.

Syntax:
putback (char c);

Example:
char ch = ‘D’;
cin.peek(‘F’);
cin.putback (ch);

Program to implement the usage of peek() and putback() functions


#include <iostream>
using namespace std;
int main()
{
char ch1;
cout<<"Enter a sentence : " ;
while (cin.get(ch1))
{
if (ch1=='A')
cin.putback('Z');
else
cout<<ch1;

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
14

}
}
When the above code is compiled and executed, it produces the following result:
Enter a sentence : This Basket contains 1000 Apples
This Basket contains 1000 Zpples

f) read()
The read() function is a member function of istream class and is mainly used with input streams
such as cin.read(). It comes under the category of unformatted Input function. The read()
function does enter into the memory some bytes without any formatting.

Syntax:
read (char* s, streamsize n);

Example:
char Text[15];
cin.read(Text ,15);

g) gcount()
The gcount() is a member function of istream class which tries to return the number of
unformatted characters that is last extracted.

Syntax:
streamsize gcount() const;

Program to implement the usage of read() and gcount() functions


#include <iostream>
using namespace std;
const int length = 100;
int main()
{
char Text[length];
cout<<"Enter Text :"<<endl;
cin.read(Text,25);
cout<<"The text that is entered is "<<endl;
cout.write(Text, cin.gcount());
cout<<endl;
}

When the above code is compiled and executed, it produces the following result:
Enter Text : This is my first program on gcount function
The text that is entered is

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
15

This is my first program

4. Functions of <ostream> class


Some of the most commonly used functions of <ostream> class are put() and write().

a) put()
The put() function is a member function of ostream class. It is mainly used to write a character to
output device. The put() function is used with an object of ostream class.

Syntax:
put (char c);

Example:
cout.put(ch1);

Program to implement the usage of put() function


#include <iostream>
using namespace std;
int main()
{
cout.put('M').put('U').put('M').put('B').put('A').put('I').put(' \n');
char* City = "Cochin";
cout<<City<<endl;
cout.put(*City);
cout<<"\n";
char city1 [] = "DELHI";
for ( int i = 0; i<5;i++)
cout.put(city1[i]);
cout.put('\n');
cout.put(70)<<endl; //outputs F character because ASCII value of 70 is F
return 0;
}
When the above code is compiled and executed, it produces the following result:
MUMBAI
Cochin
C
DELHI
F

b) write()
The function write() is a member function of ostream class and is mainly used with output
streams such as cout.write(). It comes under the category of unformatted Output function. The

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
16

write() function output of a number of bytes from the character array in the memory without any
formatting.

Syntax:
write (const char* s, streamsize n);

Example:
char Text[30];
cout.write (Text, 30)

Program to illustrate the usage of read() and write() functions


#include <iostream>
using namespace std;
int main()
{
char sentence [] = "Go to Playground";
cout.write(sentence , 13).put('\n');
char ch1[] = "A";
cout<<"ch1 = ";
cout.write(ch1,1)<<endl;
char CH1[] = "ABCDEFGHIJO";
cout.write(CH1, 5)<<endl;
char Text[30];
cout<< "Enter the Text ";
cin.read(Text ,30);
cout.write(Text,30)<<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Go to Playgro
ch1 = A
ABCDE
Enter the Text This is a program on read() and write() functions

This is a program on read() an

5. Summary

 C++ includes a hierarchy of classes called as Stream classes that are mainly used to
describe various streams to deal with console and disk files.

 The stream classes are stated in the iostream or iostream.h header file.

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
17

 The ios class is the base class for the istream and ostream classes.

 The istream and ostream classes are in turn base classes for the class iostream, i.e.,
Input/Output Stream.

 The ios class offers the basic services that are used by all input and output classes.

 The istream class declare the input functions such as get(), getline(), read() and it also
include overloaded extraction operator (>>).

 The ostream class declare the input functions such as get(), getline(), read() and it also
include overloaded extraction operator (>>).
 The streambuf class also provides the methods of the class for loading the contents of the
buffer, access the contents of the buffer, flush the contents of the buffer, organizing the
memory of the buffer.
 The filebuf class tries to present the necessary and basic operations that are related to
files.

 The strstreambuf class is mainly designed to hold the buffers that are related to memory.

 C++ language consists of 3 _withassign classes, they are istream_withassign,


ostream_withassign and iostream_withassign.

 The _withassign classes basically consist of assignment operators.

 The cin is mainly used to get the input from standard input device, such as keyboard.

 The cout is mainly used to display the output to standard output device, such as monitor
or screen.
 The cerr is mainly used for standard error to display on monitor or screen.
 The clog is mainly used for buffered error to display on monitor.
 The cin object object of istream class along with extraction operator ( >>) is mainly used
for the input of primary types.
 It is possible with the cin object to overload the extraction operator (>>) for the user
defined types, but it can be used for the class of input object.
 The cout object of ostream class is used for standard output along with overloaded
insertion operator <<.
 The cout object can be used for user defined data, but it is must that the overloading
functions for operator << are to be described by the programmer for the class of the
objects being that are dealt with.

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
18

 The cerr object is said to be “connected” to the standard error device, which is a display
screen or monitor, but, since, the cerr object is un-buffered, therefore, each stream
insertion to cerr causes its output to come into view instantly.
 The cerr object can also be used in combination with the stream insertion operator.
 The clog object is said to be connected to the standard error device, which is a display
screen, but because, the predefined object clog is buffered, therefore, each insertion to
clog might effects its output to be seized in a buffer until the buffer is full or until the
buffer is flushed.
 The get() function is a member function of istream class is mainly used to read a single
character from an input device.
 The get() function with no arguments tries to enter one character from the selected
streams including whitespace and it tries to return the character as the value of the
function call.
 The get() function with a character argument tries to enter the next character from the
input stream including whitespace.
 The get() function with two arguments tries to read first n-1 characters one after another
into the buffer.
 When the get() function is used with three arguments, then, if the delimiter character is
met, then the function stops reading the further characters, even though the number (n –
1) is not reached.
 The getline() function eliminates the delimiter from the stream, but it does not store it in
the character array.
 The ignore() function reads and it tries to rejects up to n characters or up to the reading of
delimiter character or end of file whichever occurs first.
 The peek() function returns the next character from an input stream, but it does not take
out the character from the stream.
 The putback() function tries to return the formerly read character to the input stream.
 The read() function does enter into the memory some bytes without any formatting.
 The gcount() is a member function of istream class which tries to return the number of
unformatted characters that is last extracted.
 The put() function is mainly used to write a character to output device.
 The write() function output of a number of bytes from the character array in the memory
without any formatting.

C and C++ Programming


Electronic Science
36. C++ I/O System Basics
19

C and C++ Programming


Electronic Science
36. C++ I/O System Basics

You might also like