Monday, April 17, 2017

C++ Input/Output : Streams

In this article, you will learn about Streams Based Input/Output in C++ .

The input/output operations which involve keyboard as input device and screen as output device are known as Console I/O operations . The input/output operations which involve file as input device and output device are known as File I/O operations
C++ Input/Output implement concept of stream .It is an object-oriented alternative to C's FILE-based streams from the C standard library.Stream is the sequences of bytes or flow of data , which acts as a source from which the input data can be obtained by a program or a destination to which the output data can be sent by the program.

Input Stream :

It is flow of data bytes from a device (e.g Keyboard , disk drive) to main memory

Output Stream :

It is flow of data bytes from main memory (i.e program) to a device

Stream Class Hierarchy

Stream class is the collection of data and the methods necessary to control and maintain flow of data or stream .These stream class are declared in the header file iostream.h . The different stream class available in C++ are defined in following hierarchical order.

Unformatted I/O operations

Unformatted I/O operation do not allow user to read or display data in desired format. The unformatted operations supported by C++ are :

Overloaded operator << and >>

The insertion operator (<<) and extraction operator (>>) are overloaded operations which are used for reading and writing data to/from input/output. The predefined object cout is an object of ostream class. The ostream is said to be connected with standard output devices (i.e screen).The cout is used in conjunction with insertion (<<) operator . The C++ compiler also determines the data type of variable to be output ans selects the appropriate stream insertion operator to display data

The predefined object cin is an object of istream class. The istream is said to be connected with standard input devices (i.e keyboard).The cin is used in conjunction with extraction(>>) operator . The C++ compiler also determines the data type of input data ans selects the appropriate stream extraction operator to read data

put() and get() functions

The class istream defines get() and ostream defines put() to read and display single character

getline() and write() function

The getline reads the whole line untile the enter key is encountred and write() display the whole line
cin.getline(string_variable , size);
cout.write(string , size);

Formatted Console I/O Operations:

Member Functions of ios class and flags :

Member Function Function Syntax
width() The default width of your output will be just enough space to print the number, character, or string in the output buffer. You can change this by using width(). Because width() is a member function, it must be invoked with a cout object. It only changes the width of the very next output field and then immediately reverts to the default. cout.width(w);
Precision() It used to set the number of integers displayed after a decimal point. cout.precision(w);
setf() This is another function of ios class which is used to set various flags used for formatting text in C++ .The function takes two arguments as follows:cout.setf(argument1 ,argument2) where argument1 is one of the formatting flags defined in the class ios , which is used to specify action on the output and argument2 is known as bit field that specifies the group to which the formatting flags belongs
unsetf() This is another function of ios class which is used to unset various flags used for formatting text in C++ .The function takes two arguments as follows:cout.unsetf(argument1)

List of ios flags :

Description of format Flags Bit field
Left justified output ios::left ios:adjusted
Right justified output ios::right ios:adjusted
Padding after sign ios::intrenal ios:adjusted
Scientific notation ios::scientific ios:floatfield
Fixed point notation ios::fixed ios:floatfield
Decimal base ios::dec ios:basefield
Octal base ios::oct ios:basefield
Hexadecimal base ios::hex ios:basefield


User-defined manipulators:

Sunday, April 16, 2017

Exception Handling

In this article, you will learn about Exception Handling in C++ and which handle run time error.

Exception Handling is the mechanism that separate the code that detects and handle exceptions at run time from rest of program

C++ exception handling is built upon three keywords: try, catch, and throw.

Exception Handling vs Traditional Error Handling

Following are main advantages of exception handling over traditional error handling.

1) Separation of Error Handling code from Normal Code:

In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow.

2) Functions/Methods can handle any exceptions they choose:

A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it)

3) Grouping of Error Types:

In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.

Exception Handling Model

The error handling mechanism perform following task :

  • Find the problem (Hit the Exception)
  • Inform that error has occured (Throw the exception)
  • Receive the error information (Catch the exception)
  • Take corrective ations (Handle the exception)

Try Block

A try/catch block is placed around the code for which particular exception will be analysed and detected.It is followed by one or more catch blocks . The try block doesn't define how we are handling an exception but it merely tells the program , "if you see an exception in the following code , grab it". If the try block detects exception , the exception is thrown to catch block using throw keyword and program control also transfer to catch block , it never returns to try blocks again. If no error is found within try block , catch block is escaped .

//code to be monitered.

Throw Block

An exception is thrown in a particular catch block using throw keyword. It can throw object of different types , known as exception objects.

When try blocks is executed , whenever exceptions are found they are thrown through throw blocks and the program leaves the try block and enters into the catch blocks . If type of object thrown in try block match the argument type in the catch statement ,
the catch block are executed to handle those exception . If no match catch are found , then program is aborted with the help of abort() function which is invoked by default

Catch Block

The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch.

catch ()
//block of statement that handles the exception

Rethrowing an Exception

If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression (throw without assignment_expression) causes the originally thrown object to be rethrown.

Because the exception has already been caught at the scope in which the rethrow expression occurs, it is rethrown out to the next dynamically enclosing try block. Therefore, it cannot be handled by catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the dynamically enclosing try block have an opportunity to catch the exception.


This program implement Rethrowing an Exception


Caught Exception

Saturday, April 15, 2017


In this article, you will learn about Templates in C++ and it's useful for generic programming in C++.

Templates are a feature of the C++ programming language that allows single functions and classes to handle different data types. This helps you to write generic programs.

Generic Programming

Generic programming is a style of computer programming in which program are not compiled as it is but rather 'Templates' of source code are transform into source code at the time of compilation according to supplied datatype as parameters

In Templates of C++ template of class or function is defined with general data type and is replaced by a specified data type at the time of actual use of class or function , Hence it follow Generic programming

An Example to Begin With

This program add two number of different data type according to type of supplied argument


Result of adding two float : 13.7

Result of adding two integer : 13

At the time of compilation 'a' is replaced by datatype according to supplied data type such as :

int add (int c , int d)
      int sum ;
   sum = c + d ;
   return sum; 

Type of Templates:

  • Function Templates
  • Class Templates

Function Templates:

Function Template is a template which is used to define function which can handle arguments of different types in different

This avoids overhead of rewriting a function having body of same patterns but operating for different data types.Defining a function template contains two steps

Defining general data type :

template <class template_name>

Defining a function with general data type :

template_name function_name(arguments.....)
//body of function with data type

Example program of Function Templates:

Q) Use Template to add two integers , two floats and one integer and one float respectively and display final result in float


Result of adding two integer : 13

Result of adding two float : 13.7

Result of adding one integer and one float : 13.2

Q) Find the sum and average of elements in an array using function templates


Result of adding  integer array : 73

Result of average of  integer array : 12

Result of adding  float array : 74.1

Result of average of  float array : 12.35

Class Templates:

A class template is a kind of class which has member of template type and the actual type of data being manipulated will be specified as a parameter when the object of that class will be created

Template classes provide mechanism for creating applications with generic types , which are common applications such as lists ,stacks and queues etc .Defining a class template contains three steps

Defining template :

template <class template_name>

Defining class with members of template type :

class class_name {
// class member with datatypes template_name whenever appropriate

Defining objects :

class_name <specific_data_type> object_name

Example program of Class Templates:

Q) Use Class Template to add data of different data type


Passing integer :
The sum  is :7
Passing float :
The sum  is :73.68

Q) Create Stack Using Class Template


Exception: Stack<>::pop(): empty stack

Standard Template Library:

Standard Template Library is a software library for the C++ programming language that mainly operate in data providing container to manage collection of objects of a certain type , algorithms to perform actions on object of container , and iterators to steps through elements of container.


Containers are used to manage collections of objects of certain kind. There are several different types of containers like list , map , vector etc


Algorithms act on containers . They provide means by which we will perform initialization , sorting , searching etc


Iterators are used to step through elements of collections of objects . These collections may be containers or subsets of containers

Example program of Standard Template Library:

Q) Use Vector to create array of integer


Leatest pushed element is :12

The size of array is : 2

Element at position '0' is :32