You are on page 1of 59

Mailam Engineering College, Mailam.

Department of Information Technology


(CS2311/U-III)

UNIT III
SYLLABUS
Exception handling - Streams and formatted I/O – file handling – namespaces – String
Objects - standard template library.

PART – A
1) What are Exceptions?
Exception refers to unexpected condition in a program. The unusual
conditions could be faults, causing an error which in turn causes the program
to fail. The error handling mechanism of C++ is generally referred to as
exception handling.

2) What are the two types of exceptions?


Exceptions are classifieds into
a) Synchronous exception
b) Asynchronous exception

3) What is a synchronous exception?


The exception which occur during program execution , due to some fault
in the input data or technique that is not suitable to handle the current class of
data, within the program are known as synchronous exception. For instance
errors such as out-of-range, overflow, underflow and so on.

4) What is an Asynchronous exception?


The exceptions caused by events or faults unrelated to the program and
beyond the control of the program are called asynchronous exception. For
instance, errors such as keyboard interrupts, hardware malfunctions, disk
failure, and so on.

5) What are the blocks used in the Exception Handling?


The blocks related to exception handling constructs are
 try
 throw
 catch
The keyword try is used to preface a block of statements which may generate
exceptions. This block of statements is known as try block.
When an exception is detected, it is thrown using throw statement in the try
block.
A catch block catches the exception thrown by the throw statement in the try
block and handles it appropriately.

Prepared By: S. Amutha, AP / IT, MEC. 1


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Syntax:
try
{
………
………
throw exception;
}
catch (type arg)
{ }

6) Draw the Exception handling model?

Try block

Perform operation which may


throw or invoke external function
if needed

Invoke function having throw block


Throw block
If(failure)
exception Throw object;

Catch block
exception
Catches all exceptions thrown
from within try block or by
function invoked within a try block

7) Write the syntax of try construct


The try keyword defines a boundary within which an exception can occur.A
block of code in which an exception can occur must be prefixed by the keyword
try.Following the try keyword is a block of code enclosed by braces.This indicates that
the program is prepared to test for the existence of exceptions

Keyword

try

Prepared By: S. Amutha, AP / IT, MEC. 2


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

{
//code raising exception or referring to a function raising exception
}
catch(type_id1)
{
//actions for handling an exception
}


catch(type_idn)
{
//actions for handling an exception
}

8) Write the syntax of catch construct


The exception handler is indicated by the catch keyword. It must be used
immediately after the statements marked by the try keyword. The catch handler can
also occur immediately after another catch. Each handler will only evaluate an
exception that matches, or can be covered to the type specified in its argument list.

Keyword object name or nameless object

Catch(T)
{
// actions for handling an exception
}

9) Write the syntax of throw construct


The keyword throw is used to raise an exception when an error is generated in
the computation. The throw expression initializes a temporary object of the type T (to
match the type of argument arg ) used in throw(T arg )

Named object, nameless object


Keyword

throw T;

Prepared By: S. Amutha, AP / IT, MEC. 3


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

10) List out the tasks to be performed for error handling code
1) Detect the problem causing exception (Hit the exception)
2) Inform that an error has occurred (Throw the exception)
3) Receive the error information (Catch the exception)
4) Take corrective actions (Handle the exceptions)

11) Write the steps to be performed when an exception is raised


1) The program searches for a matching handler
2) If a handler is found, the stack is unwound to that point
3) Program control is transferred to the handler
4) If no handler is found, the program will invoke the terminate()function. If no
exceptions are thrown, the program executes in the normal fashion

12) Write the syntax of specifying a list of exceptions

Function definition List of exceptions that can be raised

FunctionSpecification throw (type id1, type id2,……)


{
//Function body raising exceptions if error occurs
}

13) Write the syntax of catch all construct

Three dots:indicate catch all exceptions

Catch(…)
{
//actions for handling an exception
}

Prepared By: S. Amutha, AP / IT, MEC. 4


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

14) What is a secure operation?


All destructors in a C++ program should have an empty specification
throw().This is called secure operations

15) What is stack unwinding?


The process of calling destructor for automatic objects constructed on the path
from a try-block to a thrown expression is called stack unwinding

16) What are the functions supported by C++ to handle uncaught exceptions ?
The functions supported by C++ to handle uncaught exceptions are
 terminate ( )
 set_terminate ( )
 unexpected ( )
 set_unexpected ( )
17) What are streams?
A Stream is a sequence of bytes. It can 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 stream source that provides data to the program is called the input stream
and the destination stream that receives output from the program is called output
stream.
18) What are the stream classes for console operations?
a)ios
b)istrean
c)ostream
d)iostream
e)streambuf
19) Draw the console stream classes for hierarchy
ios

istream streambuf ostream

iostream

istream_withassign iostream_withassign ostream_withassign

Prepared By: S. Amutha, AP / IT, MEC. 5


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

20) List out some of the unformatted I/O operators.


a)put()
b)get()
c)getline()
d)write()

21) List out some of the formatted I/O operations


C++ supports a number of feature that could be used for formatting the
output.These features include
a)ios stream class member functions and flags
b)Standard manipulators
c)User –defined manipulators

22) List some of the ios functions


a)width()
b)precision()

c)fill()
d)setf()
e)unsetf()

23) List some of the non-parameterized manipulators


a)dec
b)hex
c)oct
d)es
e)endl
f)ends
g)flush

24) What is custom/user-defined manipulators


The users can design their own manipulators to control the appearance of the
output

25) Write the syntax of creating a custom manipulator


Ostream & manipulator(ostream & output, arguments_if_any)
{
……
……(manipulator code)
……
Return output; }

Prepared By: S. Amutha, AP / IT, MEC. 6


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

26) List out some of the manipulators


a)setw(int width)
b)setprecision(int prec)
c)setfill(int fchar)
d)setbase(int base)
e)setiosflags(long flags)
f)resetioflags(long flags)

27) What are the flags that do not have bit fields?
a)ios::showbase-Use base indicator on output
b)ios::showpos-Print + before positive integers
c)ios::showpoint-Show trailing decimal point and zeros
d)ios::uppercase-Use uppercase letters for hex output
e)ios::unitbuf-Flush all streams after insertion
g)ios::stdio-Flush stdout and stderr after insertion

28) What are the two types of data communication?


a) Data transfer between the console unit and the program
b) Data transfer between the program and disk file

29) What are the functions that the file stream class provides?
a)seekg()-Moves get pointer to a specified location
b)seekp()-Moves put pointer to a specified location
c)tellg()-Gives the current position of the get pointer
d)tellp()-Gives the current position of the put pointer

30) What is a file?


A file is a collection of related information defined by its creator. Files represent
programs (both source and object forms) and data.Data may be numeric,alphabetic, or
alphanumeric.Files may be free-form,such as text files,or may be rigidly formatted.

31) List some of the file modes


1)ios::in
2)ios::out
3)ios::ate
4)ios::app
5)ios::trunk
6)ios::nocreate
7)ios::noreplace
8)ios::binary

Prepared By: S. Amutha, AP / IT, MEC. 7


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

32) What is meant by namespace?


ANSI C++ Standard has added a new keyword namespace to define a scope that
could hold global identifiers.The best example of namespace scope is the C++
Standard Library.All classes,functions and templates are declared within the
namespace named std.
Using namespace std;

The using namespace statement specifies that the members defined in std namespace
will be used frequently throughout the program

33) Write the syntax for defining a namespace

namespace namespace_name
{
//Declaration of
//variables,functions,classes,etc.
}

34) What is unnamed namespaces?


An unnamed namespace is one that does not have a name. Unnamed
namespace members occupy global scope and are accessible in all scopes following the
declaration in the file

35) What is Standard Template Library?


The collection of these generic classes and functions is called the Standard
Template Library

36) List the components of STL


The STL contains several components. They are
1)Containers
2)Algorithms
3)Iterators

37) What is container?


A container is an object that actually stores data.It is a way data is organized in
memory. The STL containers are implemented by template classes and therefore can
be easily customized to hold different types of data

38) What is an algorithm?

Prepared By: S. Amutha, AP / IT, MEC. 8


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

An algorithm is a procedure that is used to process the data contained in the


containers. The STL includes many different kinds of algorithms to provide support to
tasks such as initializing, searching, copying, and sorting and merging

39) What is an iterator?


An iterator is an object that points to an element in a container. We can use
iterators to move through the contents of containers.Iterators are handled just like
pointers

40) What are the three types of containers?


The STL contains three types of containers
1)Sequence containers
2)Associative containers
3)Derived containers

41) What is meant by sequence containers?


Sequence containers store elements in a linear sequence, like a line. Each
element is related to other elements by its position along the line. They all expand
themselves to allow insertion of elements and all of them support a number of
operations on them

Element0 Element1 Element2 …..Last Element

42)What are the types of sequence containers


The STL provides three types of sequence containers
1)Vector
2)list
3)deque

43) What is meant by Associative Containers?


Associative containers are designed to support direct access to elements
using keys.

44) What are the types of Associative containers?


The STL provides three types of associative containers
1)Set
2)Multiset
3)Map

Prepared By: S. Amutha, AP / IT, MEC. 9


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

4)Multimap
45) What is meant by Derived Containers?
The derived containers do not support iterators and therefore we cannot
use them for data manipulation. They support two member functions pop() and push()
for implementing deleting and inserting operations.
46) What are the types of derived containers
The STL provides three types of derived containers
1)Stack
2)Queue
3)Priority_queue
47) What is meant by vector?
The vector stores elements in contiguous memory locations and enables direct
access to any element using the subscript operator[].A vector can change its size
dynamically and therefore allocates memory as needed at run time
48) What is meant by lists?
The list is another container that is popularly used. It supports a bidirectional,
linear list and provides an efficient implementation for deletion and insertion
operations.
49) What is meant by maps?
A map is a sequence of pairs where a single value is associated with each
unique key. Retrieval of values is based on the key and is very fast. We should specify
the key to obtain the associated value.

Key1 Value1

Key2
Value2

. .
. .
. .
. .
. .
Key N
.
. ValueN

Prepared By: S. Amutha, AP / IT, MEC. 10


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

50) Write the member functions of the map class


begin ()
clear()
empty()
end()
erase()
find()
insert()
size()
swap()

51) What are the advantages of using C++ IO over C IO


C++ IO is object oriented.
C++ IO stream contains rich ser of formatting options
C++ IO is much easier to use.

52) What is the use of Namespace aliases?


 It is possible to provide an assumed name for namespaces.
 Aliases are useful for shortening very long fully qualified names.
 Stream is a series of bytes, which act either as a source from which input
data can be extracted or as a
 destination to which the output can be sent.

 The source stream provides data to the program called the input stream
and the destination stream that
 receives data from the program is called the output stream.

53) What is meant by Koenig lookup?


It is the ability of the compiler to find out exact namespace of the object in use
even when not specified by the programmer. The compiler uses an algorithm called
augment dependent lookup also known as koenig lookup to find out objects even if it
is not mentioned either using directive or using declaration.

54) List the limitations of using character array.


Strings are implemented in C as character arrays. There are some limitations of
using character arrays. They are:
They can not be compared with other strings like String1 == String2
They cannot be assigned like normal variables like String1=String2
Initializing with other string is not directly possible.

Prepared By: S. Amutha, AP / IT, MEC. 11


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

55) What are the two types of associative containers?


Set: This type of containers only store the keys
Map: It stores elements as well as keys
Advantages of using containers
 Small in number: They are very few and so are easy to master
 Generality: They are general in nature
 These software components are efficient, Tested, Debugged and
Standardized
 They are portable and reusable

56) Give few ios class functions and flags ?

Function Task performed

Specifies the required number of fields to be used while displaying the


Width( )
output value.
Precision ( ) Specifies the number of digits to be displayed after the decimal point.
Fill ( ) Specifies a character to be used to fill the unused area of a field. By
default, fills blank space character.
Setf ( ) Sets format flag that control the form of output display.
Unsetf ( ) Clears the specified format flag.

57) Storing programs and data permanently in main memory is not preferred .
Give reasons .
 Main memory is usually too small to permanently store all the needed programs
and data.
 Main memory is a volatile storage device, which loses its contents when power
is turned off.

58) What is a file?


A file is a collection of related information defined by its creator. Commonly files
represent programs (both source and object forms) and data. Files may be free-form,
such as text files or may be rigidly formatted. In general, a file is a sequence of bits,
bytes, lines, or records whose meaning is defined by its creator and user.

59) What do you mean by sequential access?


A sequential file has to be accessed sequentially; to access the particular data
in the file all the preceding data items have to be read and discarded. For example a
file on a tape must be accessed sequentially.

Prepared By: S. Amutha, AP / IT, MEC. 12


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

60) What do you mean by random access?


A random file allows access to the specific data without the need for accessing
its preceding data items. However, it can be accessed sequentially. For example, a file
on a hard disk or floppy disk can be accessed either sequentially or randomly.

PART – B

1. Explain briefly about exception handling mechanism.


 Definition of Exception handling.
 Various traditional error handling methods.
 Need for exception handling.
 Components involved in exception handling mechanism.
 Tasks of Error handling mechanism
 Challenges of exception handling approach
 Drawbacks of exception handling approach

1.1 Definition of Exception handling:


Exception:
 Exception is an error like situation. Exception refers to unexpected condition in a
program.
 The unusual conditions could be faults, causing an error which in turns causes
the program to fail.

Exception Handling
 Exception handling is a mechanism provided by C++ to handle when an exception
occurs.

Exception Handler
 The catch block which is executed when a specific exception is thrown

Exception Specification
 A list contained in the ( ) braces after the function header and throw keyword. The
contents of the list are the only valid type of exceptions that can be thrown from
that function.

Exceptions are of Two Kinds


1) Synchronise exception (out of range index & overflow)
2) Asynchronies exception.(Error caused by event beyond the control of the
program.)

Prepared By: S. Amutha, AP / IT, MEC. 13


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

EXAMPLE: Keyboard interrupts.

NOTE: C++ design to handle only synchronise exception.

1.2 Various traditional error handling methods:


Traditional error handling is done in three different ways.
1) Returning Error Number
2) Global flag Manipulation
3) Abnormal Termination

1. Returning Error Number


 To write a function we use arguments. If something wrong in the argument, the
function returns an error code.
 If the function returns zero value then it is successful function call and if other
than zero it indicates error relayed to the value returned. There is no universal
standard for such error codes

2. Global flag Manipulation


 There is an error variable, which is globally available to all C library functions.
They can set the value of error variable to indicate error.
 After calling the library function, we can check the value of error variable to find
out actual error.
 The disadvantage of using this method is the user has to test the value of the
global flag every time the function is called. If the user does not check the error
variable and continues to work, the user may get an unexpected result.

3. Abnormal Termination
 Whenever something goes wrong, we call exit ( ) or abort ( ) function to terminate
the execution of the program, which displays an error message before terminating.
Use of this procedure means, that an error would eventually crash the program.

1.3 Need for exception handling.


 Exception handling mechanism is needed in C++ because of inappropriateness of
all the traditional solutions while working with objects and in distributed
environment.
The following concept stresses on the needs of exception handling:
 Dividing the error handling: The Library designer and library user
 Unconditional termination and programmer preferred termination
 Separating error reporting and error handling.
 The object destroy problem.

Prepared By: S. Amutha, AP / IT, MEC. 14


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

1.4 Components involved in exception handling mechanism.


C++ Exception handling mechanism is basically built upon three keywords namely
o Try -Indicating program area where exception can be thrown.
o Throw -Throwing an exception
o Catch-Actually taking an action for the specific exception.

Try-Block
 Try block throw an exception.
 Code need to be monitored is placed within the try block
 Try block contains either a throw statement or a function containing either a
throw statement or a similar function inside the body.
try
{
//code for raising exception
}

Catch-Block
 This is the section where the exception is handled.
 Within the try block, by an explicit throw statement or by calling a function
with such a throw statement, exception is said to be thrown.
 The exception is handled by the catch section.
 The catch section should immediately follow the try block.
catch (type arg)
{
//statements for managing exceptions
}

Throw –Block
 This is a mechanism to generate the exception with the keyword throw
 The identifier following throw is a name of variable being thrown.

throw (exception);
throw exception;
throw;

1.5 Tasks of error handling mechanism


 Detect the problem causing exception(Hit exception)
 Inform that an error has occurred (Throw an exception)
 Receive the error information(Catch the exception)

Prepared By: S. Amutha, AP / IT, MEC. 15


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

 Take corrective actions(Handle the exception)


1.6 Challenges of exception handling approach
 Finding proper handler
 Finding proper handler for a polymorphic object
 Backtracking till the beginning of try block
1.7 Drawbacks of exception handling approach
 Exception handling mechanism has a major drawback of uncertain termination
 Exception handling is a overhead
 Using third party libraries is in danger of a program crash.
 Mobile device programmers do not use exception handling.

2. Explain how multiple catch of an exception is done using a suitable C++


program is done.
It is possible to use more than one catch block for a single try block to handle
different exceptions
# include <iostream> switch(reply)
# include<conio> {
using namespace std; case 1:
class MyException throw 10;
{ case 2:
int Exnumber; throw „a‟;
string Exmessage; case 3:
public: throw Error1;
MyException(int errno, string errmsg) }
{ catch(int x)
ExNumber=errno; {
ExMessage=errmsg; cout<<”integer exception”<<x;
} }
void ShowEx( ) catch(char c)
{ {
cout<<”Error number cout<<”character exception”<<c;
is”<<Exnumber; }
cout<<”Exception is”<< catch (MyException my)
ExMessage; {
} cout<<”Object Exception”<<my.show( );
}; }
void ExGen( ) }
{ void main( )
MyException Error1(10,”Error Testing”); {
cout<<”Press 1 for int 2 for char 3 for ExGen( );
object”; }
int reply;
cin>>reply;

Prepared By: S. Amutha, AP / IT, MEC. 16


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

3. Explain how catch all exception is done using a suitable C++ program
It is possible to catch all types of exception in a single catch section.
# include <iostream> switch(reply)
# include<conio> {
using namespace std; case 1:
class MyException throw 10;
{ case 2:
int Exnumber; throw „a‟;
string Exmessage; case 3:
throw Error1;
public: }
MyException(int errno, string catch(….)
errmsg) //Catching all exceptions
{ {
ExNumber=errno; cout<<”Anything thrown caught
ExMessage=errmsg; here”;
} }
}
void ShowEx( )
void main( )
{
{
cout<<”Error number
ExGen( );
is”<<Exnumber;
}
cout<<”Exception is”<<
ExMessage;
}
};

void ExGen( )
{
MyException Error1(10,”Error
Testing”);
cout<<”Press 1 for int 2 for char 3
for object”;
int reply;

cin>>reply;

Prepared By: S. Amutha, AP / IT, MEC. 17


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

4. Explain how rethrowing is done using a suitable C++ program [Nov/Dec 2009]
To catch the exception in the function N and also to pass it to any other
function, re-throw an exception after catching it.
# include <iostream> //throw exception
# include<conio> case 3:
using namespace std; throw Error1;
class MyException //throw exception }
{ catch(int x){
int Exnumber; throw; //re-throw exception
string Exmessage; }
public: catch(char c) {
MyException(int errno, string errmsg) throw; //re-throw exception
{ }
ExNumber=errno;
catch (MyException my){
throw; //re-throw exception
ExMessage=errmsg;
}
}
}
void ShowEx( )
void main( )
{
{
cout<<”Error number
try {
is”<<Exnumber;
ExGen( );
cout<<”Exception is”<<
}
ExMessage; catch(int)
} {
}; cout<<”integer exception”;
}
catch(char)
void ExGen( ) {
{ cout<<”character exception”<<;
MyException Error1(10,”Error }
Testing”); catch (MyException my)
cout<<”Press 1 for int 2 for char 3 for {
object”; cout<<”Object
int reply; Exception”<<my.show( );
cin>>reply; }
switch(reply) }
{
case 1:
throw 10;
// throw exception
case 2:
throw „a‟;

Prepared By: S. Amutha, AP / IT, MEC. 18


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

5. Explain how exception specification is done using a suitable C++ program


 It is possible to specify what kind of exceptions can be thrown by functions,
using a specific syntax.
 The general form for such declaration is

return-type function-name(argument list)throw(data type exceptions


allowed to be thrown)
{
…………..(function body)
}

Example
void ExGen( ) throw(int,char)
{
…………….
}
# include <iostream> catch (MyException my)
# include<conio> {
using namespace std; cout<<”Object Exception”<<my.show(
class MyException );
{ }
int Exnumber; }
string Exmessage;
public: void main( )
MyException(int errno, string errmsg) {
{ try
ExNumber=errno; {
ExMessage=errmsg; ExGen( );
} throw 20;
void ShowEx( ) }
{ catch(int)
cout<<”Error number {
is”<<Exnumber; cout<<”integer exception”;
cout<<”Exception is”<< }
ExMessage; catch(char)
} {
}; cout<<”character exception”<<;
}
void ExGen( ) throw(int,char) catch (MyException my)
{ {

Prepared By: S. Amutha, AP / IT, MEC. 19


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

MyException Error1(10,”Error Testing”); cout<<”Object Exception”<<my.show( );


}
cout<<”Press 1 for int 2 for char 3 for }
object”;
int reply;
cin>>reply; switch(reply)
{
case 1:
throw 10;
case 2:
throw „a‟;
case 3:
throw Error1;
}
catch(int x)
{
cout<<”integer exception”<<x;
}
catch(char c)
{
cout<<”character exception”<<c;
}

6. Explain how terminate function is done using a suitable C++ program


 When the exception handling mechanism does not get any proper catch block
for a thrown exception,
 Terminate ( ) function is called to terminate the program execution.
 It is a built in function, when it is invoked internally it calls the abort( ) function
call to cancel the program execution in the event of run time error related to
exceptions.

Prepared By: S. Amutha, AP / IT, MEC. 20


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

//Terminate.cpp catch(int x)
# include <iostream> {
# include<conio> cout<<”integer exception”<<x;
using namespace std; }
class MyException
{ catch(char c)
int Exnumber; {
string Exmessage; cout<<”character exception”<<c;
public: }
MyException(int errno, string errmsg) catch (MyException my)
{ {
ExNumber=errno; cout<<”Object Exception”<<my.show(
ExMessage=errmsg; );
} }
void ShowEx( ) }
{ void Myterminate( )
cout<<”Error number //own terminate function
is”<<Exnumber; {
cout<<”Exception is”<< ……………………….
ExMessage; //code for file close
} exit(-1);
};
}
void main( )
{
void ExGen( )
void MyTerminate( );
{ set_terminate(My Terminate);
MyException Error1(10,”Error Testing”); ExGen( );
cout<<”Press 1 for int 2 for char 3 for }
object”;
int reply;
cin>>reply;
switch(reply)
{
case 1:
throw 10;
case 2:
throw „a‟;
case 3:
throw Error1;
}

Prepared By: S. Amutha, AP / IT, MEC. 21


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

7. What is a Stream? State the classes of Streams?


Stream:
“A stream is a conceptual pipe like structure, which can have one end attached
to the program and the other end attached by default to a keyword, screen or a file. It
is possible to change where one end is pointing to, while keeping the other end as it
is.”
A stream is a sequence of bytes. It acts as 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 output from the program is called the output
stream.

Input Stream Extraction from


Input Stream
Input Device
Program

Output Device Insertion into


Output Stream
Output Stream
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.
These classes are declared in header file iostream.

ios

istream streambuf ostream

iostream

istream_withassign iostream_withassign ostream_withassign

Prepared By: S. Amutha, AP / IT, MEC. 22


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

ios (General input/ output stream class)


 Contains basic facilities that are used by all other input and output classes.
 Also contains a pointer to a 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 properties of ios
 Declares input functions such as put() and write()
 Contains overloaded insertion operator <<
iostream (input/output stream)
 Inherits the properties of ios istream and ostream through multiple inheritance
and thus contains all the input and output functions.
streambuf
 Provides an interface to physical devices through buffers.
 Acts as a base for filebuf class used ios files.

8. List the advantages of using C++ I/O with C.


 C++ IO is object oriented. Objects represent streams in C++. Cout is an object of
output stream class while cin is an object of input stream class. C IO system
does not know anything about objects
 C++ IO stream contains richer formatting options as compared to C.
 C++ IO is much easier to use.

9. Explain about Unformatted I/O with an example program?


Cout object support unformatted output.
1. Put() and get() Member Functions for Cout:
 The classes istream and ostream define two member functions get() and
put() respectively to handle the single character input/output operations.
 The get() function is a member of istream class used to read the character
from keyboard including the blank space, tab and the newline character.
 There are two types of get() functions.
 get(char *)
o It assigns the input character to its argument.
Example:

Prepared By: S. Amutha, AP / IT, MEC. 23


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

char c;
cin.get(c); // get a character from keyboard and assign it to c
 get(void)
o It returns the input character.
Example:
char c;
c=cin.get();
The value returned by the function get() is assigned to the
variable c.
 The function put() a member of ostream class, can be used to output a line
of text, character by character.
Example:
cout.put(„x‟); // displays the character x
cout.put(ch); // displays the value of variable ch
We can also use number as an argument to the function put(). It
converts the number into corresponding character using ASCII value.
PROGRAM:
#include<iostream> Output:
using namespace std; Input
int main() Object Oriented Programming
{ Output
int count=0; Object Oriented Programming
char c; Number of characters=27
cout<<”Input Text”;
cin.get(c);
while(c!=‟\n‟)
{
cout.put(c);
count++;
cin.get(c);
}
cout<<”number of
characters=”<<count<<”\n”;
return 0;
}

Prepared By: S. Amutha, AP / IT, MEC. 24


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

2. getline() and write() Functions:


 We can read and display a line of text more efficiently using the line-
oriented input/output functions getline() and write().
 The getline() function reads a whole line of text that ends with a new line
character .
 getline() function is invoked using the object cin.
cin.getline(line,size);
o This function call reads character input into the variable line.
o The reading is terminated as soon as either the newline character
„\n‟ is encountered or size-1 characters are read.
PROGRAM:
#include<iostream> Output:
using namespace std; First Run
int main() Enter city name: Delhi
{ City name: Delhi
int size=20; Enter city name again:
char city[20]; City name now:
cout<<”Enter city name\n:”; Enter another city name: Chennai
cin>>city; New city name: Chennai
cout<<”City name:”<<city Second Run
<<”\n\n”; Enter city name: New Delhi
cout<<”Enter city name again:\n”: City name: New
cin.getline(city, size); Enter city name again:
cout<<”City name now:”<<city City name now: Delhi
<<”\n\n”; Enter another city name: Greater
cout<<”Enter another city Bombay
name:\n”: New city name: Greater Bombay
cin.getline(city, size);
cout<<”New City name:”<<city
<<”\n\n”;
return 0;
}

 The write() function displays an entire line and has the following form:
cout.write(line, size)
o The first argument line represents the name of the string to be
displayed.
o The second argument indicates the number of characters to be
display.

Prepared By: S. Amutha, AP / IT, MEC. 25


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

PROGRAM:
#include<iostream> for(i=n;i>0;i--)
using namespace std; {
int main() cout.write(string2,i);
{ cout<<”\n”;
char *string1=”C++”; }
char *string2=”Programming”; cout.write(string1,m).write(string2,n);
int m=strlen(string1); // Concatenating strings
int n=strlen(string2); cout<<”\n”;
for(int i=1;i<n;i++) cout.write(string1,10);
{ // Crossing the boundary
cout.write(string2,i); return 0;
cout<”\n”; }
}

10. Explain about Formatted I/O with an example program?


Definition:
“These functions are defined in the ios-base class and are useful in formatting.
Being member functions, they are called by following a dot (.) after the cout object”.
C++ supports number of features that could be used for formatting the output.
They includes,
 ios class functions and flags
 Manipulators
 User-defined output functions.
The ios class contains a large number of member functions that would help us to
format the number of ways. Some of them are,
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.
unsetf() To clear the flags specified.

Defining Field Width: width()


Width() function is used to define the width of a field necessary for output of an
item.
cout.width(w);

Prepared By: S. Amutha, AP / IT, MEC. 26


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

w is the field width (number of columns)


This function can specify the field width for only one item.
Eg:
cout.width(5);
cout<<543<<12”\n”; corresponding output 5 4 3 1 2 is
Another Example is,
cout.width(5);
cout<<543;
cout.width(5);
cout<<12”\n”; corresponding output 5 4 3 1 2 is

Setting Precision: precision ()


It is used to specify the number of digits to be displayed after the decimal point
while printing the floating point numbers.

cout.precision(d);
d is the number of digits to the right of the decimal point.
Eg:
cout.precision(3);
cout<<sqrt(2)<<”\n”;
cout<<3.14159<<”\n”;
cout<<2.50032<<”\n”;
The corresponding output will be,
1.141 (truncated)
3.142 (rounded to the nearest cent)
2.5 (no trailing zeros)
Filling and Padding: fill ()
fill() function is used to fill the unused positions by any desired character.
cout.fill(ch);
ch represents the character which is used for filling the unused positions.
Eg:
Cout.fill(„*‟);
Cout.width(10);
Cout<<5250<<”\n”;
The output will be * * * * * * 5 2 5 0

Program:
#include<iostream>
using namespace std;
int main()
{

Prepared By: S. Amutha, AP / IT, MEC. 27


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

cout.fill(„<‟);
cout.precision(3);
for(int n=1;n<=6;n++)
{
cout.width(5);
cout<<n;
cout.width(10);

cout<<1.0/float(n)<<”\n”;
if(n==3)
cout.fill(„>‟);
}
cout<<”Padding changed”;
cout.fill(„#‟);
cout.width(15);
cout<<12.345678<<”\n”;
return 0;
}
Output:
<<<<1<<<<<<<<<1
<<<<2<<<<<<<0.5
<<<<3<<<<<0.333
>>>>4>>>>>>0.25
>>>>5>>>>>>>0.2
>>>>6>>>>>0.167
Padding changed
#########12.346

Formatting Flags, Bit-fields and setf ()


Setf stands for set flags.
Cout.setf(arg1,arg2)
arg1 is one of the formatting flags defined in the class ios. The formatting flag
specifies the format action required for the output.
Another ios constant, arg2 known as bit field specifies the group to which the
formatting flag belongs.
Cout.sef(ios::left, ios::adjustfield);
Cout.setf(ios::scientific, ios::floatfield);
Note: First argument should be one of the group members of the second argument.

Prepared By: S. Amutha, AP / IT, MEC. 28


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Eg:
Cout.fill(„*‟);
Cout.setf(ios::left, ios::adjustfield);
Cout.width(15);
Cout<<”TABLE 1”<<”\n‟;
Output will be: T A B L E 1 * * * * * * * *

Displaying Trailing zeros and plus sign


If we print the numbers 10.75,25.00 and 15.50 using a field width of say, eifght
positions with two digits precision then the output will be,
1 0 . 7 5
2 5
1 5 . 5
Note that the trailing zeros in the second and third items have been truncated.
The setf() can be used with the flag ios::showpoint as a single argument to
achieve this form of output.
Eg:
Cout.setf(ios::showpoint);
Similarly a plus sign can be printed before a positive number using the
following statements,
Cout.setf(ios::showpos);
Eg;
Cout.setf(ios::showpoint);
Cout.setf(ios::showpos);
Cout.precision(3);
Cout.setf(ios::fixed, ios::floatfield);
Cout.setf(ios::internal, ios::adjustfield);
Cout.width(10);
Cout<<275.5<<”\n”;
Output is:
+ 2 7 5 . 5 0 0

11. What are Manipulators? Explain managing output with manipulators and also
design your own manipulators with example.
Functions which are non-member but provide similar formatting mechanism as
ios functions are called Manipulators.
 The header file iomanip provides a set of functions called manipulators which
can be used to manipulate the output formats.
 They provide the same features as that of the ios member functions and flags.

 The most commonly used manipulators are,

Prepared By: S. Amutha, AP / IT, MEC. 29


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Manipulator 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 fill()
setiosflags(long f) Set the format flag f setf()
resetiosflags(long f) Clear the flag specified by f unsetf()
endl Insert new line and flush stream “\n”
Eg;
Cout<<setw(10)<<12345;
PROGRAM:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout.setf(ios::showpoint);
cout<<setw(5)<<”n”
<<setw(15)<<”Inverse of n”
<<setw(15)<<”Sum of terms\n”;
double term, sum=0;
for(int n=1;n<=10;n++)
{
term=1.0/float(n);
sum=sum+term;
cout<<setw(5)<<n
<<setw(14)<<setprecision(4)
<<setiosflags(ios::scientific)<<term
<<setw(13)<<resetiosflags(ios::scientific)
<<sum<<endl;
}
return 0;
}
Output:
N Inverse of n Sum of terms
1 1.0000e+000 1.0000
2 5.0000e-001 1.5000
3 3.3333e-001 1.83333

Prepared By: S. Amutha, AP / IT, MEC. 30


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Designing our own Manipulators


We can create our own manipulators for certain purposes. The general form for
creating our own manipulators is,

ostream &manipulator (ostream &output)


{


retun output;
}
Here the manipulator is the name of the manipulator under creation.
Eg:
ostream & unit ( ostream &output)
{
output<<”inches”;
return output;
}
The statement cout<<36<<unit; will produce a output as 36 inches.
PROGRAM:
#include<iostream>
#include<iomanip>
using namespace std;
ostream & currency ( ostream &output)
{
output<<”Rs”;
return output;
}
ostream & form ( ostream &output)
{
output.setf(ios::showpos);
output.setf(ios::showpoint);

output.fill(„*‟);
output.precision(2);
output<<setiosflags(ios::fixed)<<setw(10);
return output;
}
int main()
{
cout<<currency<<form<<7864.5;
return 0;

Prepared By: S. Amutha, AP / IT, MEC. 31


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

}
Output: Rs**+7864.50

DIFFERENCE BETWEEN MANIPULATORS AND ios FUNCTIONS:


 Unlike ios functions, manipulators do not return the previous status.
 We can write our own manipulator and use it in the program.
 ios functions are single. They cannot be combined to have multiple effects
together. Manipulators are easy to write and produce more readable code.
 ios functions require nothing else then<iostream> file to be included, whereas
manipulators need <iomanip> file to be included additionally.
 For some manipulators, there is no equivalent ios function.
 When a manipulator does not take an argument. It is passed without ( )
parenthesis.ios functions cannot be called without parenthesis
 Some of the manipulators are needed in pairs to provide the toggle effect.
 ios functions are member functions, while manipulators are non-member
functions.

12. What is Namespace and explain about it with an example.

NAMESPACE
Namespace is used to define the scope that could hold global identifiers.
The best example of namespace scope is the C++ Standard Library.
using namespace std;

It specifies that the members defined in std namespace will be used frequently
throughout the program.

Defining Namespace
The syntax for defining the namespace is as similar to the syntax for defining
class.
namespace namespace_name
{
// Declaration of Variables, Functions, Classes, etc.
}
Eg:
namespace TestSpace
{
int m;
void display(int n)
cout<<n;
}

Prepared By: S. Amutha, AP / IT, MEC. 32


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

The variable m and the function display are inside the scope by the TestSpace
namespace. If we want to assign the value for m we mst use the scope resolution
operator,
TestSpace::m=100;

We can also use a using directive to simplify the access.


using namespace namespace_name; // using directive
using namespace_name::member_name; // using declaration

Nesting of Namespace:
A namespace can be nested within another namespace.
Eg:
namespace NS1
{
…………
…………
namespace NS2
{
int m=100;
}
…………
…………
}
To access the variable m,
cout<<NS1::NS2::m;
Or
using namespace NS1;
cout<<NS2::m;

Unnamed Namespaces
An unnamed namespace is one that does not have a name. It occupy global
scope and are accessible in all scopes following the declaration in the file.

PROGRAM:

#include<iostream>
using namespace std;
namespace Name1
{
double x=4.56;

Prepared By: S. Amutha, AP / IT, MEC. 33


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

int m=100;
namespace Name2
{
double y=1.23;
}
}
namespace
{
int m=200;
}
int main()
{
cout<<”x=”<<Name1::x<<”\n”;
cout<<”m=”<<Name1::m<<”\n”;
cout<<”y=”<<Name1::Name2::y<<”\n”;
cout<<”m=”<<m<<”\n”;
return 0;
}

Output:
x = 4.56
m = 100
y= 1.23
m =200

13. What is STL? List the three types of containers.


Standard Template Library
The STL is a generic library, meaning that its components are heavily
parameterized, almost every component in the STL is a template.
STL is the collection of Generic classes and functions.
Containers
 A container is an object that actually stores data.
 It is a way data is organized in memory.
 The STL containers are implemented by template classes and therefore can be
easily customized to hold different types of data.
 The STL defines 10 containers which are grouped into three categories,
 Sequence Containers
 Associative Containers
 Derived containers

Prepared By: S. Amutha, AP / IT, MEC. 34


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

1. Sequence Containers
 It stores elements in a linear sequence.
 Each element is related to other elements by its positions along the line.
Element 0 Element 1 Element 2 Last Element

begin() end()
The STL provides three types of Sequence containers:
 vector
o A dynamic array.
o Allows insertions and deletions at back.
o Permits direct access to any element.
 list
o A bidirectional linear list.
o Allows insertions and deletions anywhere.
 Deque
o A double-ended queue.
o Allows insertions and deletions at both the ends.
o Permits direct access to any element.
2. Associative Containers
 It are designed to support direct access to elements using keys.
 They are not sequential.
They are of four types,
 set
o Used for storing unique sets.
o Allows rapid lookup.
 multiset
o Used for storing non-unique sets.
These both containers can store a number of items and provide
operations for manipulating them using the values as the keys.
 map
o Used for storing unique key/value pairs.
o Each key is associated with only one value.
o Allows key based lookup.
 multimap
o Used ofr storing key/value pairs in which one key may be
associated with more than one values.
o Allows key based lookup.
These both are used to store pairs of items, one called the key and the
other called the value.

Prepared By: S. Amutha, AP / IT, MEC. 35


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

3. Derived Containers
 The STL provides three derived containers
 stack
 queue
 priority_queue
 They are also known as container adapters.

14. What is an Iterator. Explain with its types?


Iterators
 Iterators behave like pointers and are used to access container elements.
 They are often used to traverse from one element to another, a process known
as iterating through the container.
 Five types of iterators
 Input
 Output
o It both supports the least functions.
o They can be used only to traverse in a container.
 Forward
o It supports all operations of input and output iterators and also
retain their position in the container.
 Bidirectional
o It provides the ability to move in the backward direction in the
container.
 Random
o It combines the functionality of a bidirectional iterator with an
ability to jump to an arbitrary location.

15. What is an Algorithm in STL?


Algorithms
 Algorithms are functions that can be used generally across a variety of
containers for processing their contents.
 STL algorithms reinforce the philosophy of reusability.
 It must include <algorithm>
 STL algorithms based on the nature of operations they perform may be
categorized as,
 Retrieve or non-mutating algorithms
 Mutating algorithms
 Sorting algorithms
 Set algorithms
 Relational algorithms
Some of them are:

Prepared By: S. Amutha, AP / IT, MEC. 36


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

1. Non mutating algorithms


count() – Counts occurrence of a value in a sequence
equal() – True if two ranges are same
find() – Finds first occurrence of a value in a sequence
for_each() – Apply an operation to each element
2. Mutating algorithms
copy() – Copies a sequence
fill() – Fills a sequence with a specified value
remove() – Deletes elements of a specified value
reverse() – Reverse the order of elements
3. Sorting algorithms
binary_search() – Conducts a binary search on an ordered sequence
merge() – Merges two sorted sequences
sort() – Sorts a sequence
4. Set algorithms
includes() – Finds whether a sequence is a subsequence of another
set_difference() – Constructs a sequence that is the difference of two ordered
sets
5. Relational algorithms
equal() – Finds whether two sequence are the same
max() – gives maximum of two values
max_element() – Finds the maximum element with an sequence

16. Write a C++ program by using Vector class template.


#include <iostream>
#include <vector>
#include <string>

using namespace std;

main()
{
vector<string> SS;

SS.push_back("The number is 10");


SS.push_back("The number is 20");
SS.push_back("The number is 30");

Prepared By: S. Amutha, AP / IT, MEC. 37


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

cout << "Loop by index:" << endl;

int ii;
for(ii=0; ii < SS.size(); ii++)
{
cout << SS[ii] << endl;
}

cout << endl << "Constant Iterator:" << endl;

vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
cout << *cii << endl;
}

cout << endl << "Reverse Iterator:" << endl;

vector<string>::reverse_iterator rii;
for(rii=SS.rbegin(); rii!=SS.rend(); ++rii)
{
cout << *rii << endl;
}

cout << endl << "Sample Output:" << endl;

cout << SS.size() << endl;


cout << SS[2] << endl;

swap(SS[0], SS[2]);

Prepared By: S. Amutha, AP / IT, MEC. 38


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

cout << SS[2] << endl;


}

Output:
Loop by index:
The number is 10
The number is 20
The number is 30

Constant Iterator:
The number is 10
The number is 20
The number is 30

Reverse Iterator:
The number is 30
The number is 20
The number is 10

Sample Output:
3
The number is 30
The number is 10

17. How can we create string objects?


We can create string objects in a number of ways as illustrate below:

String s1; //using constructor with no argument


String s2(“xyz”); //using one-argument constructor
S1=s2; //assigning string objects
S3=”abc”+s2 //concatenating strings
Cin>>s1; //reading through keyboard(one word)
Getline(cin,s1); //reading through keyboard a line of text
The overloaded +operator concatenates two string objects.we can also
use the operator += to append a string to the end of a string.
Example:
S3 +=s1; //s3 = s3+ s1
S3 +=”abc”; //s3 =s3+ “abc”
The operator << and >> are overloaded to handle input and output of string
objects.

Prepared By: S. Amutha, AP / IT, MEC. 39


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Examples:
Cin >> s2;
Cout << s2;
Getline (cin,s2);
Example program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
string s2( “new”);
string s3( “delhi”);
s1=s2;
cout<<”s1=”<<s1<<”\n”;
s1=”standard c++”;
cout <<”now s1=”<<s1<<”\n”;
string s4(s1);
cout << “s4=”<<s4<<”\n\n”;
cout <<”ENTER A STRING \n”;
cin>>s4;
cout <<now s4=”<< s4<<”\n\n”;
s1=s2+s3;
cout<< “s1 finally contains: “<<s1 <<‟\n”;
return 0;
}

Output:

S1 = new
Now s1 = standard C++
S4 = standard C++
Enter a string
Computer centre
Now s4 =computer
S1 finally contains: New Delhi

Prepared By: S. Amutha, AP / IT, MEC. 40


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

18. How we manipulate string objects? Explain with an example program.


We can modify contents of string objects in several ways, using the member
functions such as insert (), replace (), erase (), and append ().
Example program:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1(“12345”);
string s2(“abcde”);
cout << “original strings are: \n”;
cout <<”s1:”<<s1<<”\n”;
cout <<”s2:”<<s2<<”\n\n”;
cout<<”place s2 inside s1 \n”;
s1.insert(4,s2);
cout<<”modified s1:”<<s1<<\n\n”;
cout<<”remove 5 characters from s1 \n”;
s1.erase(4,5);
cout<<”now s1:”<<s1<<”\n\n”;
cout<<”replace middle 3 characters in s2 with s1 \n”;
s2.replace(1,3,s1);
cout<<”now s2:”<<s2<<”\n”;
return 0;
}

Output:
Original strings are:
S1: 12345
S2: abcde
Place s2 inside s1
Modified s1: 1234abcde5
Remove 5 characters from s1
Now s1: 12345
Replace middle 3 characters in s2 with s1
Now s2: a12345e

Prepared By: S. Amutha, AP / IT, MEC. 41


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

19. Write a Program by using Relational operations on String Objects?


A number of operators that can be used on string are defined for string objects.
The operators =and + for creating objects.
Example program:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1(“ABC”);
string s2(“XYZ”);
string s3 = s1+ s2;
if(s1 != s2)
cout << “s1 is not equal to s2 \n”;
if(s1 >s2)
cout <<”s1 greater than s2 \n”;
else
cout <<”s2 greater than s1 \n”;
if(s3 ==s1+s2)
cout<<”s3 is equl to s1+s2 \n\n”;
int x= s1.compare(s2);
if(x ==0)
cout << “s1 ==s2 \n”;
else if(x > 0)
cout << “s1 >s2 \n”;
else
cout << “s1 < s2 \n”;
return 0;
}

Output:
S1 is not equal to s2
S2 greater than s1
S3 is equal to s1+s2
S1<s2

Prepared By: S. Amutha, AP / IT, MEC. 42


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

20. Write a C++ program to obtain string characteristics and accessing


characters in strings?

String Characteristics
Class string support many functions that could be used to obtain the
characteristics of string such as,

Size and length:


The size or length denotes the number of elements currently stored in a given
string.
Capacity:
The capacity indicates the total elements that can be stored in the given string.

Example program:
#include<iostream>
#include<string>
using namespace std;
void display(string, &str)
{
cout << “size =”<<str.size() << “\n”;
cout <<”length = “<<str.length() << “\n”;
cout << “capacity =” << str.capacity() << “\n”;
cout << “maximum size = “<< str.max_size() << “\n”;
cout << “empty =”<< str.empty() ? “yes” : “no”);
cout << “\n\n”;
}
int main()
{
string str1;
cout << “initial status: \n”;
display (str1);
cout << “enter a string (one word) \n”;
cin>> str1;
cout <<”status now: \n”
display(str1);
str1.resize (15);
cout<<”status after resizing: \n”;
display(str1);
cout<< “\n”;
return 0;
}

Prepared By: S. Amutha, AP / IT, MEC. 43


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Output:
Initial status:
Size = 0
Length = 0
Capacity = 0
Maximum size = 4294967293
Empty: yes
Enter a string (one word)
India
Status now:
Size = 5

Length =5
Capacity = 31
Maximum size = 4294967293
Empty: no
Status after resizing:
Size = 15
Length =15
Capacity =31
Maximum size = 4294967293
Empty: no

Accessing characters in Strings


We can access substrings and individual characters of a string in several ways.
The string class supports the following functions for this purpose:
At () for accessing individual characters
Substr () for retrieving a substring
Find () for finding a specified substring
Find_first_of() find location of first occurrence of the specified
characters
Find_last_of() find location of last occurrence of the specified characters

Example program:
#include<iostream>
#include<string>
Using namespace std;
Int main()
{
String s(“ONE TWO THREE FOUR”);
Cout << “the string contains:\n”;

Prepared By: S. Amutha, AP / IT, MEC. 44


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

For (int i=0;i<s.length();i++)


Cout<<s.at(i);
Cout<<”\n string is shown again:\n”;
For(int j=0;j<s.length();j++)
Cout<<s[j];
Int x1=s.find(“TWO”);
Cout <<”\n\n TWO is found at:”<<x1<<”\n”;
Int x2 = s.find_first_of(„T‟);
Cout <<”\n T is found first at: “<< x2<<”\n”;
Int x3 = s.find_last_of(„R‟);
Cout <<”\n R is last found at: “<<x3<<”\n”;
Cout <<”\n retriv and print substring TWO \n”;
Cout << s.substr(x1,3);
Cout << “\n”;
Return 0;
}

Output:
The string contains:
ONE TWO THREE FOUR
String is shown again:
ONE TWO THREE FOUR
TWO is found at :4
T is found first at : 4
R is found last at : 17
Retrieve and print substring TWO
TWO

21. Write a C++ Program for Comparing and Swapping strings?

The string supports functions for comparing and swapping strings.


 The compare () function can be used to compare either two strings or portions
of two strings.
 The swap () function can be used for sapping the contents of two string objects.

Example program:
#include<iostream>
#include<string>
using namespace std;
int main()

Prepared By: S. Amutha, AP / IT, MEC. 45


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

string s1 (“road”);
string s2 (“read”);
string s3 (“red”);
cout<< “s1 = “<<s1<< “\n”;
cout<< “s2 = “<<s2<< “\n”;
cout<< “s3 = “<<s3<< “\n”;
int x = s1.compare(s2);
if(x==0)
cout<< “s1 == s2” << “\n”;
else if(x>0)
cout << “s1 > s2” << “\n”;
else
cout<< “s1 < s2” <<”\n”;
int a = s1.compare (0,2,s2,0,2);
int b = s2.compare (0,2,s1,0,2);
int c = s2.compare (0,2,s3,0,2);
int d = s2.compare (s2.size()-1,1,s3,s3.size()-1,1);
cout<<”a =” << a << “\n” << “b = “<< b << “\n”;
cout<<”c =” << c << “\n” << “d = “<< d << “\n”;
cout<<”\n befoe swap: \n”;
cout<< “s1 = “ << s1 << “\n”;

cout<< “s2 = “ << s2 << “\n”;


s1.swap(s2);
cout<<” \n after swap: \n”;
cout<< “s1 = “ << s1 << “\n”;
cout<< “s2 = “ << s2 << “\n”;
return 0;
}
Output:
s1 = road
s2 = read
s3 = red
s1>s2
a=1
b = -1
c=0
d=0
Before swap:
s1 = road
s2 = read

Prepared By: S. Amutha, AP / IT, MEC. 46


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

After swap:
s1 = read
s2 = road

22. Explain the File I/O streams with an example.

File I/O with Streams:


Many real-life problems handle large volumes of data, therefore we need to use
some devices such as floppy disk or hard disk to store the data.

The data is stored in these devices using the concept of files. A file is a
collection of related data stored in a particular area on the disk.

Programs can be designed to perform the read and write operations on these
files.

A program typically involves either or both of the following kinds of data


communication:
1.Data transfer between the console unit and the program.
2. Data transfer between the program and a disk file.
3. The input/output system of C++ handles file operations which are very much
similar to the console input and output operations.

It uses file streams as an interface between the programs and the files.

The stream that supplies data to the program is known as input stream and the
one that receives data from the program is known as output stream.

In other words, the input stream extracts or reads data from the file and the
output stream inserts or writes data to the file.

Classes for the file stream operations :


The I/O system of C++ contains a set of classes that define the file handling
methods.

These include ifstream, ofstream and fstream.

These classes, designed to manage the disk files, are declared in fstream.h and
therefore we must include this file in any program that uses files.

Prepared By: S. Amutha, AP / IT, MEC. 47


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Details of some useful classes :


filebuf
Its purpose is to set the file buffer to read and write. Contains openprot
constant used in the open() of the filestream classes. Also contains close() and open()
as member functions.

fstreambase
Provides operations common to the file streams. Serves as a base for fstream, ifstream
and ofstream classes. Contains open() and close() functions.

ifstream
Provides input operations. Contains open() with default input mode. Inherits the
functions get(), getline(), read(), seekg() and tellg() functions from istream.

ofstream
Provides output operations. Contains open() with default output mode. Inherits
put(), seekp(), tellp(), and write() functions from ostream.

fstream

Prepared By: S. Amutha, AP / IT, MEC. 48


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Provides support for simultaneous input and output operations. Contains


open() with default input mode. Inherits all the functions from istream and ostream
classes through iostream.

The ifstream, ofstream and fstream classes are declared in the file fstream.h
The istream and ostream classes are also included in the fstream.h file.

23. How will you open and close a file.

Opening and closing a file :


For opening a file, we must first create a file stream and than link it to the
filename.

A filestream can be defined using the classes ifstream, ofstream, and fstream
that are contained in the header file fstream.h

A file can be opened in two ways:


1. Using the constructor function of the class. This method is useful when we
open only one file in the stream.

2. Using the member function open() of the class. This method is used when we
want to manage multiple files using one stream.

Using Constructor
Create a file stream object to manage the stream using the appropriate class.
That is, the class ofstream is used to create the output stream and the class ifstream
to create the input stream.

Initialize the file object with the desired filename, e.g.:

ofstream outfile(“sample.txt”);

The above statement creates an object outfile of class ofstream that manages the
output stream. This statement also opens the file sample.txt and attaches it to the
output stream for writing.

Similarly, the statement declared in as an ifstream object and attaches to the


file “sample.txt” for reading.

ifstream infile(“sample.txt”);

Prepared By: S. Amutha, AP / IT, MEC. 49


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Program: Writing and reading data into file, using constructors

# include
void main()
{
ofstream outfile(“sample.txt”); // create file for output
char ch = „a‟;
int i = 12;
float f = 4356.15;
char arr[ ] = “hello”;
outfile << ch << endl <<<="" endl="" f="" arr;="" send="" the="" data="" to="" file
outfile.close();

ifstream infile(“sample.txt”);

infile >> ch >> i >> f >> arr; // read data from file

cout << ch << i << f << arr; // send data to screen


}

To write data into the file, character by character.

#include
#include
void main()
{
char str[]=“C++ is superset of C. It is an object-oriented /
programming language.”;

ofstream outfile(“sample2.txt”); // Open the file in write mode

for(int i = 0; i < strlen(str); i++)


outfile.put(str[i]); // write data into the file, character by character.
}

Prepared By: S. Amutha, AP / IT, MEC. 50


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

26. How will you read and write objects of classes in a File.
Writing and reading Objects of a class :
So far we have done I/O of basic data types. Since the class objects are the
central elements of C++ programming, it is quite natural that the language supports
features for writing and reading from the disk files objects directly.

The binary input and output functions read() and write() are designed to do
exactly this job.

The write() function is used to write the object of a class into the specified file
and read() function is used to read the object of the class from the file.

Both these functions take two arguments:


1. address of object to be written.
2. size of the object.

The address of the object must be cast to the type pointer to char.

One important point to remember is that only data members are written to the disk
file and the member functions are not.

Writing an object into the file

#include
class Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout << “\n Enter name:”; cin >> name;
cout << “\n Enter age:”; cin >> age;
}
} ; // End of the class definition

void main()
{

Prepared By: S. Amutha, AP / IT, MEC. 51


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

Person per ; // Define an object of Person class

per.getData(); // Enter the values to the data members of the class.

ofstream outfile(“Person.txt”); // Open the file in output mode

outfile.write((char*)&per, sizeof(per)); // Write the object into the file


}

fstream object can be used for both input & output.

In the open() function we include several mode bits to specify certain aspects of the file
object.

app -> To preserve whatever was in the file before. Whatever we write to the file will be
appended to the existing contents.

We use in and out because we want to perform both input and output on the file.

eof() is a member function of ios class. It returns a nonzero value if EOF is


encountered and a zero otherwise.

25. What are file pointers and their Manipulators?


File pointers and their manipulations:
Each file has two associated pointers known as the file pointers.
One of them is called the input pointer or get pointer.
Other is called the output pointer or put pointer.
We can use these pointers to move through the files while reading or writing.
The input pointer is used for reading the contents of a given file location and
the output pointer is used for writing to a given file location.

Functions for manipulation of file pointers


seekg() Moves get pointer (input) to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Gives the current position of the get pointer.
tellp() Gives the current position of the put pointer.

infile.seekg(10);
Moves the file pointer to the byte number 10.

Prepared By: S. Amutha, AP / IT, MEC. 52


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

The bytes in a file are numbered beginning from zero.

Thus, the pointer will be pointing to the 11th byte in the file.

Specifying the offset :


The seek functions seekg() and seekp() can also be used with two arguments as
follows:
seekg(offset, refposition);
seekp(offset, refposition);
The parameter offset represents the number of bytes the file pointer to be
moved from the location specified by the parameter refposition.
The refposition takes one of the following these constant defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file.

Parameters of open() function

Parameter Meaning
ios::app Append to end of the file
ios::ate Go to end of the file on opening
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exists
ios::out Open file for writing only
ios::trunc Delete contents of the file if it exists

26. Write a C++ program to demonstrate file handling as follows: get strings as
input from the user, store them in a file, retrieves them and displays them.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
string * split(string, char);
const char FileName[] = "c://TestAddress/TestAddress.txt";

Prepared By: S. Amutha, AP / IT, MEC. 53


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

ifstream myAddress(FileName);
string name = " ";
string address = " ";
string street= " ";
string city = " ";
string state = " ";
string zipCode = " ";
int record = 0;
ofstream outMyAddress(FileName, ios::out);
int main ()
{
menu();
return 0;
} //end main
void menu(void)
{
//allow user to choose to append records, display records or exit the program
char userChoice = ' ';
//Display Menu
system("cls");
cout << "\nName and Address database:" << endl;
cout << endl;
cout << "\n\n(A)ppend record, (S)how Record, (E)xit:";
cin >> userChoice;
//Users Choice
switch (userChoice)
{
case 'a':
case 'A'://Append Record
myAddress.open (FileName, ios::app);
if (myAddress.is_open())
{
writeData();
}
break;
case 's':
case 'S'://Show record
myAddress.open (FileName, ios:: in);
if (myAddress.is_open())
{
readData();

Prepared By: S. Amutha, AP / IT, MEC. 54


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

}
break;
case 'e':
case 'E'://Exit
myAddress.close();
break;
default:
cout << "Invalid choice" << endl;
cout << endl << endl << endl;
break;
}
return;
}//end menu
void writeData(void) //Write the Address Info to a file
{
char answer = ' ';
char response = ' ';
if(myAddress.is_open())
{
//entering loop
while (answer != 'n' || answer != 'N')
{
cout << endl;
getline(cin, name);
cout << "\nEnter name: ";
getline(cin, name);
cout << "\nEnter Street: ";
getline(cin, street);
cout << "\nEnter City: ";
getline(cin, city);
cout << "\nEnter State: ";
getline(cin, state);
cout << "\nEnter Zip Code: ";
getline(cin, zipCode);
cout << endl;
outMyAddress << name << ", " << street << " ," << city << ", " << state << " ," <<
zipCode << endl;
record++;
cout << "\nWould you like to enter another record? (Y/N)" << endl;
cin >> response;
if (response == 'n' || response == 'N')

Prepared By: S. Amutha, AP / IT, MEC. 55


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

{
return menu();
}
}
}
myAddress.close();
void readData(void)
{
ifstream inMyAddress(FileName, ios::in);
if(myAddress.is_open())
{
string firstLine;
inMyAddress >> firstLine;
getline (myAddress, firstLine, '\n');
cout << endl;
cout << "Reading the file(s)..." << endl;
cout << endl;
cout << "Record #: " << record << endl;
string *theField = split(firstLine, ',');
cout << "Name......" << theField[0] << endl;
cout << "Street......" << theField[1] << endl;
cout << "City......" << theField[2] << endl;
cout << "State......" << theField[3] << endl;
cout << "Zip Code......" << theField[4] << endl;
}
inMyAddress.close();
system("pause");
return menu();
}
string * split(string theLine, char theDeliminator){
int splitCount = 0;
for(int i = 0; i < ((int)theLine.size()); i++){
if (theLine[i] == theDeliminator)
splitCount++;
return 0;
}
splitCount++;
string* theFieldArray;
theFieldArray = new string[splitCount];
string theField = "";
int commaCount = 0;

Prepared By: S. Amutha, AP / IT, MEC. 56


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

for(int i = 0; i < ((int)theLine.size()); i++){


if (theLine[i] != theDeliminator) {
theField += theLine[i];
}
else {
theFieldArray[commaCount] = theField;
theField = "";
commaCount++;
}
}
theFieldArray[commaCount] = theField;
return theFieldArray;
}

University Questions

PART – A

1. What are IO streams? Give an example. (Nov/Dec 2010)


Refer Q.No:17

2. What is the purpose of the STL (Standard Template Library)? (Nov/Dec 2010)
Refer Q.No:36

3. What are manipulators? How do you create a one? (Nov/Dec 2011)


Refer Q.No:24 & 25

4. How is an Exception handled in C++. (Nov/Dec 2010-CSE)


Refer Q.No:5 and 6

PART – B

1. Write a C++ program to demonstrate file handling as follows: get strings as


input from the user, store them in a file, retrieves them and displays them.
(Nov/Dec 2010)
Refer Q.No:22

2. Explain the exception handling mechanism available in C++ with suitable


examples. Refer Q.No:1
(Nov/Dec 2010)

Prepared By: S. Amutha, AP / IT, MEC. 57


P. Mathivanan, AP/IT, MEC.
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-III)

3. Explain the features of I/O system supported in C++. (10) (Nov/Dec


2011)
Refer Q.No:8

4. Write a program that contains a possible exception. Use a try block and throw
it and a catch block to handle it properly. (6)
(Nov/Dec 2011) Refer Q.No:3

5. Write a program that reads a name from the keyboard into three separate
string objects and then concatenates them into a new string object using „+‟
operator and append() function. (10)
(Nov/Dec 2011)
Refer Q.No:19

6. List the major categories of containers supported by STL. (6) (Nov/Dec 2011)
Refer Q.No:13

7. Explain the different type of Exception. How will u handle Exceptions?


Explain with example program. )
(Dec/Jan 2009 MCA)
Refer Q.No:1, 2 and 3

8. Explain the use of Manipulators with example. (6) (Nov/Dec 2010-CSE)


Refer Q.No:11

9. Discuss in detail the unformatted I/O Operations? (10) (Nov/Dec 2010-CSE)


Refer Q.No:9

Prepared By: S. Amutha, AP / IT, MEC. 58


P. Mathivanan, AP/IT, MEC.

You might also like