SlideShare a Scribd company logo
MODULE 5
EXCEPTION HANDLING ,THE C++ I/O SYSTEM
BASICS, FILE I/O
INTRODUCTION
 we know that is very rare that a program works correctly first time .
 It might have bugs.
 The two most common types of bugs are logic errors and syntactic errors.
 The logic errors occur due to poor understanding of the problem and solution
procedure.
 The syntactic problems or errors arise due to poor understanding of the language
itself.
 we can detect these errors by using exhaustive debugging and testing procedures.
 We often come across some peculiar problems other than login or syntax errors.
 They are known as exception.
INTRODUCTION
 Exceptions are run-time anomalies or unusual conditions that a program may
encounter while execution.
 Anomalies might include conditions such as division by zero, access the array outside of
its bounds or size, or running out of memory or disk space when a program
encounters an exceptional condition.
 It is very important that it is identified and dealt with, ANSI C++ language provides
built-in language features to detect and handle exceptions which are basically run time
errors.
INTRODUCTION
 Exception handling allows you to manage run-time errors in an orderly fashion.
 Using exception handling, your program can automatically invoke an error-handling
routine when an error occurs.
 The principal advantage of exception handling is that it automates much of the error-
handling code that previously had to be coded "by hand" in any large program.
EXCEPTION HANDLING FUNDAMENTALS
 C++ exception handling is built upon three keywords: try, catch, and throw.
 In the most general terms, program statements that you want to monitor for exceptions
are contained in a try block.
 If an exception (i.e., an error) occurs within the try block, it is thrown (using throw).
 The exception is caught, using catch block and processed.
 The following discussion elaborates upon this general description.
 Code that you want to monitor for exceptions must have been executed from within a
try block. (Functions called from within a try block may also throw an exception.)
 Exceptions that can be thrown by the monitored code are caught by a catch statement,
which immediately follows the try statement in which the exception was thrown.
EXCEPTION HANDLING FUNDAMENTALS
 When a program encounters an abnormal situation for which it is not designed, the
user may transfer control to some other part of the program that is designed to deal
with the problem.
 The try block must be followed immediately by a handler, which is a catch block.
 If an exception is thrown in the try block the program control is transferred to the
appropriate exception handler.
 The program should attempt to catch any exception that is thrown by any function.
 The relationship between these three exception-handling constructs called the
exception-handling model is shown in the figure
EXCEPTION HANDLING FUNDAMENTALS
EXCEPTION HANDLING FUNDAMENTALS:The general form of try and
catch
try {
// try block
}
catch (type1 arg) {
// catch block
}
catch (type2 arg) {
// catch block
}
catch (type3 arg) {
// catch block
}...
catch (typeN arg) {
// catch block
}
• When an exception is thrown, it is caught by its corresponding
catch statement, which processes the exception.
• There can be more than one catch statement associated with
a try.
• Which catch statement is used is determined by the type of
the exception.
• That is, if the data type specified by a catch matches that of
the exception, then that catch statement is executed (and all
others are bypassed).
• When an exception is caught, arg will receive its value. Any
type of data may be caught, including classes that you create.
• If no exception is thrown (that is, no error occurs within the
try block), then no catch statement is executed.
EXCEPTION HANDLING FUNDAMENTALS
 The general form of the throw statement is shown here:
 throw generates the exception specified by the exception.
 If this exception is to be caught, then the throw must be executed either from within a
try block itself or from any function called from within the try block (directly or
indirectly).
 Throwing an unhandled exception will cause the terminate() standard library function
to be invoked.
 By default, terminate() calls abort() to stop your program, but you can specify your own
termination handler, if you like.
throw exception;
#include <iostream>
using namespace std;
int main()
{
cout << "startn";
try
{
cout << "Inside try blockn";
throw 99; // throw an error
cout << "This will not execute";
}
catch (int i)
{ // catch an error
cout << "Caught an exception -- value is: "<<i<<endl;
}
cout << "end";
return 0;
}
start
Inside try block
Caught an exception -- value is: 99
end
--------------------------------
EXCEPTION HANDLING FUNDAMENTALS
 There is a try block containing three statements, and a catch(int i) statement that processes an integer
exception.
 Within the try block, only two of the three statements will execute: the first cout statement and the
throw.
 Once an exception has been thrown, control passes to the catch expression, and the try block is
terminated.
 That is, the catch is not called. Rather, program execution is transferred to it.
 Thus, the cout statement following the throw will never execute.
 After the catch statement executes, program control continues with the statements following the catch.
 it is the job of your exception handler to remedy the problem that caused the exception, so that
program execution can continue normally.
 In cases where the error cannot be fixed, a catch block will usually end with a call to exit() or abort(), or
otherwise terminate program execution.
EXCEPTION HANDLING FUNDAMENTALS
 An exception can be thrown from outside the try block as long as it is thrown by a
function that is called from within try block.
/* Throwing an exception from a function outside
the try block.*/
#include <iostream>
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test << "n";
if(test) throw test;;
}
int main()
{
cout << "Startn";
try
{
cout << "Inside try blockn";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i)
{ // catch an error
cout << "Caught an exception value is: "<<i<<"n";
}
cout << "End";
return 0;
}
Start
Inside try block
Inside Xtest, test is: 0
Inside Xtest, test is: 1
Caught an exception value is: 1
End
--------------------------------
EXCEPTION HANDLING FUNDAMENTALS
 A try block can be localized to a function. When this is the case, each time the function
is entered, the exception handling relative to that function is reset
#include <iostream>
using namespace std;
// Localize a try/catch to a function.
void Xtest(int test)
{
try
{
if(test) throw test;
}
catch(int i)
{
cout << "Caught Exception #: " << i << 'n';
}
int main()
{
cout << "Startn";
Xtest(1);
Xtest(2);
Xtest(0);
Xtest(3);
cout << "End";
return 0;
}
EXCEPTION HANDLING FUNDAMENTALS
 It is important to understand that the code associated with a catch statement will be
executed only if it catches an exception.
 Otherwise, execution simply bypasses the catch altogether. (That is, execution never
flows into a catch statement.)
#include <iostream>
using namespace std;
int main()
{
cout << "startn";
try
{
cout << "Inside try blockn";
cout << "Still inside try blockn";
}
catch (int i)
{ // catch an error
cout << "Caught an exception -- value is: "<<i<<endl;
}
cout << "end";
return 0;
}
CATCHING CLASS TYPES EXCEPTION
 An exception can be of any type, including class types that you create.
 Actually, in real-world programs, most exceptions will be class types rather than built-in
types.
 Perhaps the most common reason that you will want to define a class type for an
exception is to create an object that describes the error that occurred.
 This information can be used by the exception handler to help it process the error.
// Use an exception class.
#include <iostream>
#include <cstring>
using namespace std;
class MyException {
public:
char str1[80];
int val;
MyException()
{
*str1 = 0;
val = 0;
}
MyException(char *s, int e)
{
strcpy(str1, s);
val = e;
}
};
int main()
{
int i;
try
{
cout << "Enter a positive number: ";
cin >> i;
if(i<0)
throw MyException("Not Positive", i);
}
catch (MyException e)
{ // catch an error
cout << e.str1 << ": ";
cout << e.val << "n";
}
return 0;
}
Enter a positive number: -6
Not Positive: -6
--------------------------------
USING MULTIPLE CATCH STATEMENTS
 you can have more than one catch associated with a try.
 However, each catch must catch a different type of exception.
 For example, this program catches both integers and strings.
#include <iostream>
using namespace std;
void fun(int test)
{
try{
if(test)
throw test;
else
throw "Value is zero";
}
catch(int i)
{
cout << "Caught Exception #: " << i << 'n';
}
catch(const char *str)
{
cout << "Caught a string: ";
cout << str << 'n';
}
int main()
{
cout << "Startn";
fun(1);
fun(2);
fun(0);
fun(3);
cout << "End";
return 0;
}
HANDLING DERIVED-CLASS EXCEPTIONS
 You need to be careful how you order your catch statements when trying to catch
exception types that involve base and derived classes .
 because a catch clause for a base class will also match any class derived from that base.
 Thus, if you want to catch exceptions of both a base class type and a derived class type,
put the derived class first in the catch sequence.
 If you don't do this, the base class catch will also catch all derived classes.
 For example, consider the following program.
// Catching derived classes.
#include <iostream>
using namespace std;
class B
{
};
class D: public B
{
};
int main()
{
D derived;
try
{
throw derived;
}
catch(B b)
{
cout << "Caught a base class.n";
}
catch(D d)
{
cout << "This won't execute.n";
}
return 0;
}
CATCHING ALL EXCEPTIONS
 In some circumstances you will want an exception handler to catch all exceptions
instead of just a certain type.
 This is easy to accomplish. Simply use this form of catch.
catch(...) {
// process all exceptions
}
// This example catches all exceptions.
#include <iostream>
using namespace std;
void fun(int test)
{
try{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw double
}
catch(...)
{ // catch all exceptions
cout << "Caught One!n";
}
}
int main()
{
cout << "Startn";
fun(0);
fun(1);
fun(2);
cout << "End";
return 0;
}
RESTRICTING EXCEPTIONS
 You can restrict the type of exceptions that a function can throw outside of itself.
 In fact, you can also prevent a function from throwing any exceptions whatsoever.
 To accomplish these restrictions, you must add a throw clause to a function definition.
ret-type func-name(arg-list) throw(type-list)
{
// ...
}
• only those data types contained in the
comma-separated type-list may be thrown
by the function.
• Throwing any other type of expression
will cause abnormal program termination.
• If you don't want a function to be able to
throw any exceptions, then use an empty
list.
#include <iostream>
using namespace std;
// This function can only throw ints, chars, and
doubles.
void fun(int test) throw(int, char, double)
{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw double
}
int main()
{
cout << "startn";
try
{
fun(0); // also, try passing 1 and 2 to fun()
}
catch(int i)
{
cout << "Caught an integern";
}
catch(char c)
{
cout << "Caught charn";
}
catch(double d)
{
cout << "Caught doublen";
}
cout << "end";
return 0;
UNDERSTANDING TERMINATE( ) AND UNEXPECTED( )
 terminate( ) and unexpected( ) are called when something goes wrong during the
exception-handling process.
 These functions are supplied by the Standard C++ library.
 Their prototypes are shown here:
 These functions require the header <exception>.
 by default, both functions halt program execution when an exception handling error
occurs.
void terminate( );
void unexpected( );
UNDERSTANDING TERMINATE( ) AND UNEXPECTED( )
 The terminate( ) function is called whenever the exception handling subsystem fails to
find a matching catch statement for an exception.
 It is also called if your program attempts to rethrow an exception when no exception
was originally thrown.
 For example, such a circumstance could occur when, in the process of unwinding the
stack because of an exception, a destructor for an object being destroyed throws an
exception.
 In general, terminate( ) is the handler of last resort when no other handlers for an
exception are available. By default, terminate( ) calls abort( ).
 The unexpected( ) function is called when a function attempts to throw an exception
that is not allowed by its throw list. By default, unexpected( ) calls terminate( ).
THE UNCAUGHT_EXCEPTION( ) FUNCTION
 The C++ exception handling subsystem supplies one other function that you may find
useful: uncaught_exception( ).
 Its prototype is shown here:
 This function returns true if an exception has been thrown but not yet caught.
 Once caught, the function returns false.
bool uncaught_exception( );
THE C++ I/O
SYSTEM BASICS
INTRODUCTION
 C++ supports two complete I/O systems:
 one inherited from C and
 object-oriented I/O system defined by C++ (hereafter called simply the C++ I/O system).
 The different aspects of C++'s I/O system, such as console I/O and disk I/O, are actually
just different perspectives on the same mechanism.
 the I/O system inherited from C is extremely rich, flexible, and powerful.
 The C's I/O system knows nothing about objects. Therefore, for C++ to provide
complete support for object-oriented programming, it was necessary to create an I/O
system that could operate on user-defined objects.
 In addition to support for objects, there are several benefits to using C++'s I/O system
even in programs that don't make extensive (or any) use of user-defined objects.
OLDVS. MODERN C++ I/O
 There are currently two versions of the C++ object-oriented I/O library in use:
 the older one that is based upon the original specifications for C++ and
 the newer one defined by Standard C++.
 The old I/O library is supported by the header file <iostream.h>.
 The new I/O library is supported by the header <iostream>.
 For the most part the two libraries appear the same to the programmer.
 This is because the new I/O library is, in essence, simply an updated and improved
version of the old one.
 In fact, the vast majority of differences between the two occur beneath the surface, in
the way that the libraries are implemented—not in how they are used.
OLDVS. MODERN C++ I/O
 From the programmer's perspective, there are two main differences between the old
and new C++ I/O libraries.
 First, the new I/O library contains a few additional features and defines some new data
types.
 Thus, the new I/O library is essentially a superset of the old one. Nearly all programs
originally written for the old library will compile without substantive changes when the
new library is used.
 Second, the old-style I/O library was in the global namespace.
 The new-style library is in the std namespace.
C++ STREAMS
 the C++ I/O system operates through streams.
 A stream is a sequence of bytes.
 The I/O system in c++ is designed to work with a wide variety of devices including
terminals, disks, and tape drives.
 Although each device is very different, the I/O system supplies an interface to the
programmer that is independent of the actual device being accessed. This interface is
known as stream.
 A stream is a logical device that either produces or consumes information.
 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.
C++ STREAMS
 In other words, a program extracts the bytes from an input stream and inserts bytes
into an output stream as illustrated in Fig.
C++ STREAMS
 The data to the input stream can come from the keyboard or any other storage device.
 Similarly, the data in the output stream can go to any storage devices or screen.
 stream acts as an interface between the program and the I/O device. Therefore, a c++
programs handles data (input or output) independent of the devices used.
 C++ language contains several pre-defined streams that are automatically opened when a
program begins its execution.
 These include cin and cout which have been very often in our earlier programs.
 The cin operator represents the input stream connected to the standard input device (usually
the keyboard) and cout operator represents the output stream connected to the standard
output device (usually the screen).
 Note : the keyboard and the screen are default options. We can redirect streams to the other
devices or files, if necessary.
THE C++ STREAM CLASSES
 The C++ programming Input/Output(I/O) system contains a hierarchy of classes that are
used to define various streams to deal with both the disk files and console.
 These all classes are called stream classes.
 the below figure, shows the hierarchy of the stream classes used for the input and
output(I/O) operations with the console unit.
 These classes are declared in the headerfile <iostream>.
 This file should be included in all the programs that are communicate with the console unit.
THE C++ STREAM CLASSES
 The I/O classes begin with a system of template classes. Once a template class has been
defined, specific instances of it can be created.
 As it relates to the I/O library, Standard C++ creates two specializations of the I/O
template classes:
 one for 8-bit characters and
 another for wide characters.
THE C++ STREAM CLASSES
THE C++ STREAM CLASSES
 The I/O hierarchy shown is usually mentioned without the prefix basic_, that is, basic_ ios
is usually referred to as ios. The C++ I/O system is built upon two related but different
template class hierarchies.
 The first is derived from the low-level I/O class called basic_streambuf. This class supplies
the basic, low-level input and output operations, and provides the underlying support for
the entire C++ I/O system.
 The class hierarchy that you will most commonly be working with is derived from basic_ios
 This is a high-level I/O class that provides formatting, error checking, and status
information related to stream I/O.
 ios is the base class for istream (input stream) ostream( output stream) which are, in
turn, base classes for iostream (input/output stream).
THE C++ STREAM CLASSES
 The class ios(input output system) provides the basic support for formatted and
unformatted I/O (Input/output)operations.
 In C++ programming the class istream provides the facilities for formatted and
unformatted input while the class ostream (through inheritance) gives the facilities only
for formatted outputs.
 In C++ class iostream provides the facilities for handling both output and input
streams.
 There are three classes, namely,ostream_withassign, istream_withassign, and
iostream_withassign add assignment operators to these classes.
class name Contents
ios (General I/O (input
output) stream class)
include 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 file
handling formatted input and output operations
istream (input stream)
Inherits the properties of ios Declares input functions such as get()
, getline() and read(),Contains overload extraction operator >>
ostream (output stream)
Inherits the properties of ios, Declares output functions put() and
write(), Contains overloaded insertion operator <<
iostream (input/output
stream)
Inherits the properties of ios stream and ostream through multiple
inheritance thus contains all the input and output functions.
streambuf
Provides an interface to physical devices through buffers.
Acts as a base for filebuf used ios files.
THE C++ STREAM CLASSES
 I/O library creates two specializations of the template class hierarchies just described: one for
8-bit characters and one for wide characters.
 Here is a list of the mapping of template class names to their character and wide-character
versions.
C++'S PREDEFINED STREAMS
 When a C++ program begins execution, four built-in streams are automatically opened.
 They are:
 Streams cin, cout, and cerr correspond to C's stdin, stdout, and stderr.
 By default, the standard streams are used to communicate with the console.
C++STREAMS
There are mainly two types of console I/O operations form:
1. Formatted console input output (Formatted I/O)
 bytes are grouped and converted to types such as int, double, string or user-defined
types.
 In Formatted IO operations are supported via overloading the stream insertion
(<<) and stream extraction (>>) operators, which presents a consistent public IO
interface
2. Unformatted console input output
 unformatted or low-level IO, bytes are treated as raw bytes and unconverted.
FORMATTED I/O
 The C++ I/O system allows you to format I/O operations
 For example, you can set a field width, specify a number base, or determine how many
digits after the decimal point will be displayed.
 There are two different ways that you can format data.
1. using the ios class function and flags.
 Specifically, you can set various format status flags defined inside the ios class or
call various ios member functions.
2. use special functions called manipulators
3. user defined output functions
1.FORMATTING USING THE IOS MEMBERS
Formatting Flags
 Each stream has associated with it a set of format flags that control the way
information is formatted.
 The ios class declares a bitmask enumeration called fmtflags in which the following
values are defined
1.FORMATTING USING THE IOS MEMBERS
ios::showbase Uses the base indicator on output
ios::skipws flag is set, leading white-space characters (spaces, tabs, and
newlines) are discarded when performing input on a stream.
ios::left output is left justified.
ios::right output is right justified
ios::internal flag is set, a numeric value is padded to fill a field by inserting
spaces between any sign or base character
ios::oct output to be displayed in octal.
ios::hex output to be displayed in hexadecimal
ios::dec To return output to decimal, set the dec flag.
ios::uppercase Uses capital cases for output.
basefield
adjustfield
1.FORMATTING USING THE IOS MEMBERS
ios::scientific floating-point numeric values are displayed using scientific
notation
ios::fixed floating-point values are displayed using normal notation
ios::unitbuf Flushes all stream after insertion
ios::boolalpha is set, Booleans can be input or output using the keywords true
and false.
ios::showpos leading plus sign to be displayed before positive values.
ios::showpoint Shows decimal point and trailing zeros
floatfield.
1.FORMATTING USING THE IOS MEMBERS
Setting the Format Flags
 To set a flag, use the setf( ) function. This function is a member of ios. Its most common
form is shown here:
fmtflags setf(fmtflags flags);
 This function returns the previous settings of the format flags and turns on those flags
specified by flags
 stream.setf(ios::showpos);
 Here, stream is the stream you wish to affect. Notice the use of ios:: to qualify
showpos.
 Since showpos is an enumerated constant defined by the ios class, it must be qualified
by ios when it is used.
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout << 100.0; // displays +100.000
return 0;
}
+100.000
--------------------------------
Process exited after 0.3054 seconds with return
value 0
Press any key to continue . . .
1.FORMATTING USING THE IOS MEMBERS
Clearing Format Flags
 The complement of setf( ) is unsetf( ).
 This member function of ios is used to clear one or more format flags. Its general form
is
void unsetf(fmtflags flags);
 The flags specified by flags are cleared. (All other flags are unaffected.)
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::uppercase | ios::scientific);
cout << 100.12; // displays 1.001200E+02
cout.unsetf(ios::uppercase); // clear uppercase
cout << " n" << 100.12; // displays 1.001200e+02
return 0;
}
1.001200E+002
1.001200e+002
--------------------------------
Process exited after 0.1506 seconds with return value 0
Press any key to continue . . .
1.FORMATTING USING THE IOS MEMBERS
Formatting using ios functions
 The ios class contain a large number of member functions that would help us to format
the output in several ways.
 The most important ones among them are listed in below Table
Table: ios format functions
width () To specify the required fields size for displaying an output value or contents
precesion () To specify the number of digits to be displayed after the decimal point of a float value
fill () To specify a characters that are used to fill the unused portion of a field
setf()
To specify format flags that can control the form of output display (such as left-justification and
right-justification)
unsetf() To clear flags specified
1.FORMATTING USING THE IOS MEMBERS
Using width( )
 Using this function, we can specify the width of a value to be displayed in the output at the
console.
 Its prototype is
 Here, w becomes the field width, and the previous field width is returned.
 The streamsize type is defined as some form of integer by the compiler.
 After you set a minimum field width, when a value uses less than the specified width, the
field will be padded with the current fill character (space, by default) to reach the field
width.
 If the size of the value exceeds the minimum field width, the field will be overrun.
 No values are truncated.
streamsize width(streamsize w); Ex: width(5);
1.FORMATTING USING THE IOS MEMBERS
Using precision( )
 When outputting floating-point values, you can determine the number of digits of
precision by using the precision( ) function.
 Its prototype is shown here:
 Here the precision is set to p, and the old value is returned.The default precision is 6
streamsize precision(streamsize p);
1.FORMATTING USING THE IOS MEMBERS
Using fill( )
 By default, when a field needs to be filled, it is filled with spaces.
 You can specify the fill character by using the fill( ) function.
 Its prototype is :
 After a call to fill( ), ch becomes the new fill character, and the old one is returned.
char fill(char ch);
#include <iostream>
using namespace std;
int main()
{
cout.precision(4) ;
cout.width(10);
cout << 10.12345 << "n"; // displays 10.12
cout.fill('*');
cout.width(10);
cout << 10.12345 << "n"; // displays *****10.12
cout.width(10);
cout << "Hi!" << "n"; // displays *******Hi!
cout.width(10);
cout.setf(ios::left); // left justify
cout << 10.12345; // displays 10.12*****
return 0;
}
10.12
*****10.12
*******Hi!
10.12*****
--------------------------------
2.USING MANIPULATORS TO FORMAT I/O
 Manipulators are special functions that can be included in the I/O(Input output)
statements to alter the format parameters of a stream.
 As you can see by examining the table, many of the I/O manipulators parallel member
functions of the ios class.
 Many of the manipulators were added recently to C++ and will not be supported by
older compilers.
 To access manipulators that take parameters (such as setw( )), you must include
<iomanip> in your program
22 scheme  OOPs with C++ BCS306B_module5.pdf
22 scheme  OOPs with C++ BCS306B_module5.pdf
2.USING MANIPULATORS TO FORMAT I/O
Program that uses some manipulators
program uses ios member functions to achieve
the same results:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::hex, ios::basefield);
cout << 100 << "n"; // 100 in hex
cout.fill('?');
cout.width(10);
cout << 2343.0;
return 0;
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << hex << 100 << endl;
cout << setfill('?') << setw(10) << 2343.0;
return 0;
}
OVERLOADING << AND >>
 As you know, the << and the >> operators are overloaded in C++ to perform I/O
operations on C++'s built-in types.
 In the language of C++, the << output operator is referred to as the insertion operator
because it inserts characters into a stream.
 the >> input operator is called the extraction operator because it extracts characters
from a stream.
 The functions that overload the insertion and extraction operators are generally called
inserters and extractors, respectively.
OVERLOADING << AND >>
CreatingYour Own Inserters
 All inserter functions have this general form:
 the function returns a reference to a stream of type ostream.
 the first parameter to the function is a reference to the output stream.
 The second parameter is the object being inserted.
 The last thing the inserter must do before exiting is return stream.
ostream &operator<<(ostream &stream, class_type obj)
{
// body of inserter
return stream;
}
OVERLOADING << AND >>
CreatingYour Own Extractors
 Extractors are the complement of inserters.
 The general form of an extractor function is
 Extractors return a reference to a stream of type istream, which is an input stream.
 The first parameter must also be a reference to a stream of type istream.
istream &operator>>(istream &stream, class_type &obj)
{
// body of extractor
return stream;
}
C++ FILE I/O
<FSTREAM> AND THE FILE CLASSES
 To perform file I/O, you must include the header <fstream> in your program.
 It defines several classes, including ifstream, ofstream, and fstream.
 These classes are derived from istream, ostream, and iostream, respectively.
 Remember, istream, ostream, and iostream are derived from ios, so ifstream, ofstream,
and fstream also have access to all operations defined by ios
<FSTREAM> AND THE FILE CLASSES
<FSTREAM> AND THE FILE CLASSES
 When working with files in C++, the following classes can be used:
 ofstream: writing to a file
 Ifstream: reading for a file
 fstream reading/writing
<FSTREAM> AND THE FILE CLASSES
GENERAL FILE I/O STEPS
1. Include the header file fstream in the program.
2. Declare file stream variables.
3. Associate the file stream variables with the input/output sources.
4. Open the file
5. Use the file stream variables with >>, <<, or other input/output functions.
6. Close the file.
OPENING & CLOSING A FILE
 We can open a connection to the file in two ways:
1. one way is by using the open() function: is useful only when we use only one file in
the stream.
2. second way is by using the appropriate constructor: is useful when we want to
manage multiple files using one stream
 This function is a member of each of the three stream classes. The prototype for each
is shown here:
OPENING & CLOSING A FILE
filename is the name of the file; it can include a path specifier.
The value of mode determines how the file is opened.
It must be one or more of the following values defined by openmode, is an enumeration
defined by ios (through its base class ios_base.
void ifstream::open(const char *filename, ios::openmode mode = ios::in);
void ofstream::open(const char *filename, ios::openmode mode = ios::out | ios::trunc);
void fstream::open(const char *filename, ios::openmode mode = ios::in | ios::out);
OPENING & CLOSING A FILE
OPENING & CLOSING A FILE
 The following fragment opens a normal output file.
 If open( ) fails, the stream will evaluate to false when used in a Boolean expression.
 Therefore, before using a file, you should test to make sure that the open operation
succeeded.You can do so by using a statement like this
#include <fstream>
ofstream out;
out.open("test", ios::out);
#include <fstream>
ifstream file;
file.open("example.txt", std::ios::in);
if(!mystream)
{
cout << "Cannot open file.n"; // handle error
}
OPENING & CLOSING A FILE
 c++ open using constructor the ifstream, ofstream, and fstream classes have
constructors that automatically open the file.
 The constructors have the same parameters and defaults as the open( ) function.
 To close a file, use the member function close( ).
 The close( ) function takes no parameters and returns no value.
ifstream mystream("myfile"); // open file for input
mystream.close();
UNFORMATTED AND BINARY I/O
 While reading and writing formatted text files is very easy, it is not always the most efficient
way to handle files.
 Also, there will be times when you need to store unformatted (raw) binary data, not text.
put( ) and get( )
 To read and write unformatted data is by using the member functions get( ) and put( ). These
functions operate on characters.
 That is, get( ) will read a character and put( ) will write a character.
 if you have opened the file for binary operations and are operating on a char then these
functions read and write bytes of data.
istream &get(char &ch);
ostream &put(char ch);
UNFORMATTED AND BINARY I/O:READ( ) AND WRITE( )
 to read and write blocks of binary data is to use C++'s read( ) and write( ) functions.
Their prototypes are
 The read( ) function reads num characters from the invoking stream and puts them in
the buffer pointed to by buf.
 The write( ) function writes num characters to the invoking stream from the buffer
pointed to by buf.
 streamsize is a type defined by the C++ library as some form of integer. It is capable of
holding the largest number of characters that can be transferred in any one I/O
operation
istream &read(char *buf, streamsize num);
ostream &write(const char *buf, streamsize num);
UNFORMATTED AND BINARY I/O:GETLINE( )
 Another function that performs input is getline( ). It is a member of each input stream class.
 The first form reads characters into the array pointed to by buf until either num−1 characters
have been read, a newline character has been found, or the end of the file has been
encountered. The array pointed to by buf will be null terminated by getline( ).If the newline
character is encountered in the input stream, it is extracted, but is not put into buf.
 The second form reads characters into the array pointed to by buf until either num−1
characters have been read, the character specified by delim has been found, or the end of the
file has been encountered. The array pointed to by buf will be null terminated by getline( ). If
the delimiter character is encountered in the input stream, it is extracted, but is not put into
buf.
istream &getline(char *buf, streamsize num);
istream &getline(char *buf, streamsize num, char delim);
DETECTING EOF
 To detect when the end of the file is reached by using the member function eof( ),
which has this prototype:
 bool eof( );
 It returns true when the end of the file has been reached; otherwise it returns false
22 scheme  OOPs with C++ BCS306B_module5.pdf
22 scheme  OOPs with C++ BCS306B_module5.pdf
22 scheme  OOPs with C++ BCS306B_module5.pdf
22 scheme  OOPs with C++ BCS306B_module5.pdf

More Related Content

Similar to 22 scheme OOPs with C++ BCS306B_module5.pdf (20)

PPTX
Lecture 1 Try Throw Catch.pptx
VishuSaini22
 
PPTX
Exception handling
Waqas Abbasi
 
PPTX
Object Oriented Programming Using C++: C++ Exception Handling.pptx
RashidFaridChishti
 
PPTX
6-Exception Handling and Templates.pptx
SatyamMishra237306
 
PPT
F6dc1 session6 c++
Mukund Trivedi
 
PPTX
exception handling
rajshreemuthiah
 
PPTX
Web technology
Siva Priya
 
PPTX
Project on c++ programming. Bsc.cs students
226171048
 
PPTX
C++ ala
Megha Patel
 
PPTX
Exception Handling in object oriented programming using C++
Janki Shah
 
PPSX
Exception Handling
Reddhi Basu
 
PPT
Exception handling
zindadili
 
PPT
Exception handling and templates
farhan amjad
 
PDF
Exceptions ref
. .
 
PPTX
Exception handling
Abhishek Pachisia
 
PPTX
Exception handling chapter15
Kumar
 
PPT
Exception_Handling_in_C__1701342048430.ppt
arunkumarg271
 
PPT
Handling
Amit Vats
 
PPTX
Exception handling
zindadili
 
PPT
Exceptions in c++
Kuntal Bhowmick
 
Lecture 1 Try Throw Catch.pptx
VishuSaini22
 
Exception handling
Waqas Abbasi
 
Object Oriented Programming Using C++: C++ Exception Handling.pptx
RashidFaridChishti
 
6-Exception Handling and Templates.pptx
SatyamMishra237306
 
F6dc1 session6 c++
Mukund Trivedi
 
exception handling
rajshreemuthiah
 
Web technology
Siva Priya
 
Project on c++ programming. Bsc.cs students
226171048
 
C++ ala
Megha Patel
 
Exception Handling in object oriented programming using C++
Janki Shah
 
Exception Handling
Reddhi Basu
 
Exception handling
zindadili
 
Exception handling and templates
farhan amjad
 
Exceptions ref
. .
 
Exception handling
Abhishek Pachisia
 
Exception handling chapter15
Kumar
 
Exception_Handling_in_C__1701342048430.ppt
arunkumarg271
 
Handling
Amit Vats
 
Exception handling
zindadili
 
Exceptions in c++
Kuntal Bhowmick
 

Recently uploaded (20)

PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PPTX
cybersecurityandthe importance of the that
JayachanduHNJc
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
SG1-ALM-MS-EL-30-0008 (00) MS - Isolators and disconnecting switches.pdf
djiceramil
 
PPTX
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PPTX
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
cybersecurityandthe importance of the that
JayachanduHNJc
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
SG1-ALM-MS-EL-30-0008 (00) MS - Isolators and disconnecting switches.pdf
djiceramil
 
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Information Retrieval and Extraction - Module 7
premSankar19
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
Ad

22 scheme OOPs with C++ BCS306B_module5.pdf

  • 1. MODULE 5 EXCEPTION HANDLING ,THE C++ I/O SYSTEM BASICS, FILE I/O
  • 2. INTRODUCTION  we know that is very rare that a program works correctly first time .  It might have bugs.  The two most common types of bugs are logic errors and syntactic errors.  The logic errors occur due to poor understanding of the problem and solution procedure.  The syntactic problems or errors arise due to poor understanding of the language itself.  we can detect these errors by using exhaustive debugging and testing procedures.  We often come across some peculiar problems other than login or syntax errors.  They are known as exception.
  • 3. INTRODUCTION  Exceptions are run-time anomalies or unusual conditions that a program may encounter while execution.  Anomalies might include conditions such as division by zero, access the array outside of its bounds or size, or running out of memory or disk space when a program encounters an exceptional condition.  It is very important that it is identified and dealt with, ANSI C++ language provides built-in language features to detect and handle exceptions which are basically run time errors.
  • 4. INTRODUCTION  Exception handling allows you to manage run-time errors in an orderly fashion.  Using exception handling, your program can automatically invoke an error-handling routine when an error occurs.  The principal advantage of exception handling is that it automates much of the error- handling code that previously had to be coded "by hand" in any large program.
  • 5. EXCEPTION HANDLING FUNDAMENTALS  C++ exception handling is built upon three keywords: try, catch, and throw.  In the most general terms, program statements that you want to monitor for exceptions are contained in a try block.  If an exception (i.e., an error) occurs within the try block, it is thrown (using throw).  The exception is caught, using catch block and processed.  The following discussion elaborates upon this general description.  Code that you want to monitor for exceptions must have been executed from within a try block. (Functions called from within a try block may also throw an exception.)  Exceptions that can be thrown by the monitored code are caught by a catch statement, which immediately follows the try statement in which the exception was thrown.
  • 6. EXCEPTION HANDLING FUNDAMENTALS  When a program encounters an abnormal situation for which it is not designed, the user may transfer control to some other part of the program that is designed to deal with the problem.  The try block must be followed immediately by a handler, which is a catch block.  If an exception is thrown in the try block the program control is transferred to the appropriate exception handler.  The program should attempt to catch any exception that is thrown by any function.  The relationship between these three exception-handling constructs called the exception-handling model is shown in the figure
  • 8. EXCEPTION HANDLING FUNDAMENTALS:The general form of try and catch try { // try block } catch (type1 arg) { // catch block } catch (type2 arg) { // catch block } catch (type3 arg) { // catch block }... catch (typeN arg) { // catch block } • When an exception is thrown, it is caught by its corresponding catch statement, which processes the exception. • There can be more than one catch statement associated with a try. • Which catch statement is used is determined by the type of the exception. • That is, if the data type specified by a catch matches that of the exception, then that catch statement is executed (and all others are bypassed). • When an exception is caught, arg will receive its value. Any type of data may be caught, including classes that you create. • If no exception is thrown (that is, no error occurs within the try block), then no catch statement is executed.
  • 9. EXCEPTION HANDLING FUNDAMENTALS  The general form of the throw statement is shown here:  throw generates the exception specified by the exception.  If this exception is to be caught, then the throw must be executed either from within a try block itself or from any function called from within the try block (directly or indirectly).  Throwing an unhandled exception will cause the terminate() standard library function to be invoked.  By default, terminate() calls abort() to stop your program, but you can specify your own termination handler, if you like. throw exception;
  • 10. #include <iostream> using namespace std; int main() { cout << "startn"; try { cout << "Inside try blockn"; throw 99; // throw an error cout << "This will not execute"; } catch (int i) { // catch an error cout << "Caught an exception -- value is: "<<i<<endl; } cout << "end"; return 0; } start Inside try block Caught an exception -- value is: 99 end --------------------------------
  • 11. EXCEPTION HANDLING FUNDAMENTALS  There is a try block containing three statements, and a catch(int i) statement that processes an integer exception.  Within the try block, only two of the three statements will execute: the first cout statement and the throw.  Once an exception has been thrown, control passes to the catch expression, and the try block is terminated.  That is, the catch is not called. Rather, program execution is transferred to it.  Thus, the cout statement following the throw will never execute.  After the catch statement executes, program control continues with the statements following the catch.  it is the job of your exception handler to remedy the problem that caused the exception, so that program execution can continue normally.  In cases where the error cannot be fixed, a catch block will usually end with a call to exit() or abort(), or otherwise terminate program execution.
  • 12. EXCEPTION HANDLING FUNDAMENTALS  An exception can be thrown from outside the try block as long as it is thrown by a function that is called from within try block.
  • 13. /* Throwing an exception from a function outside the try block.*/ #include <iostream> using namespace std; void Xtest(int test) { cout << "Inside Xtest, test is: " << test << "n"; if(test) throw test;; } int main() { cout << "Startn"; try { cout << "Inside try blockn"; Xtest(0); Xtest(1); Xtest(2); } catch (int i) { // catch an error cout << "Caught an exception value is: "<<i<<"n"; } cout << "End"; return 0; } Start Inside try block Inside Xtest, test is: 0 Inside Xtest, test is: 1 Caught an exception value is: 1 End --------------------------------
  • 14. EXCEPTION HANDLING FUNDAMENTALS  A try block can be localized to a function. When this is the case, each time the function is entered, the exception handling relative to that function is reset #include <iostream> using namespace std; // Localize a try/catch to a function. void Xtest(int test) { try { if(test) throw test; } catch(int i) { cout << "Caught Exception #: " << i << 'n'; } int main() { cout << "Startn"; Xtest(1); Xtest(2); Xtest(0); Xtest(3); cout << "End"; return 0; }
  • 15. EXCEPTION HANDLING FUNDAMENTALS  It is important to understand that the code associated with a catch statement will be executed only if it catches an exception.  Otherwise, execution simply bypasses the catch altogether. (That is, execution never flows into a catch statement.)
  • 16. #include <iostream> using namespace std; int main() { cout << "startn"; try { cout << "Inside try blockn"; cout << "Still inside try blockn"; } catch (int i) { // catch an error cout << "Caught an exception -- value is: "<<i<<endl; } cout << "end"; return 0; }
  • 17. CATCHING CLASS TYPES EXCEPTION  An exception can be of any type, including class types that you create.  Actually, in real-world programs, most exceptions will be class types rather than built-in types.  Perhaps the most common reason that you will want to define a class type for an exception is to create an object that describes the error that occurred.  This information can be used by the exception handler to help it process the error.
  • 18. // Use an exception class. #include <iostream> #include <cstring> using namespace std; class MyException { public: char str1[80]; int val; MyException() { *str1 = 0; val = 0; } MyException(char *s, int e) { strcpy(str1, s); val = e; } }; int main() { int i; try { cout << "Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive", i); } catch (MyException e) { // catch an error cout << e.str1 << ": "; cout << e.val << "n"; } return 0; } Enter a positive number: -6 Not Positive: -6 --------------------------------
  • 19. USING MULTIPLE CATCH STATEMENTS  you can have more than one catch associated with a try.  However, each catch must catch a different type of exception.  For example, this program catches both integers and strings.
  • 20. #include <iostream> using namespace std; void fun(int test) { try{ if(test) throw test; else throw "Value is zero"; } catch(int i) { cout << "Caught Exception #: " << i << 'n'; } catch(const char *str) { cout << "Caught a string: "; cout << str << 'n'; } int main() { cout << "Startn"; fun(1); fun(2); fun(0); fun(3); cout << "End"; return 0; }
  • 21. HANDLING DERIVED-CLASS EXCEPTIONS  You need to be careful how you order your catch statements when trying to catch exception types that involve base and derived classes .  because a catch clause for a base class will also match any class derived from that base.  Thus, if you want to catch exceptions of both a base class type and a derived class type, put the derived class first in the catch sequence.  If you don't do this, the base class catch will also catch all derived classes.  For example, consider the following program.
  • 22. // Catching derived classes. #include <iostream> using namespace std; class B { }; class D: public B { }; int main() { D derived; try { throw derived; } catch(B b) { cout << "Caught a base class.n"; } catch(D d) { cout << "This won't execute.n"; } return 0; }
  • 23. CATCHING ALL EXCEPTIONS  In some circumstances you will want an exception handler to catch all exceptions instead of just a certain type.  This is easy to accomplish. Simply use this form of catch. catch(...) { // process all exceptions }
  • 24. // This example catches all exceptions. #include <iostream> using namespace std; void fun(int test) { try{ if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } catch(...) { // catch all exceptions cout << "Caught One!n"; } } int main() { cout << "Startn"; fun(0); fun(1); fun(2); cout << "End"; return 0; }
  • 25. RESTRICTING EXCEPTIONS  You can restrict the type of exceptions that a function can throw outside of itself.  In fact, you can also prevent a function from throwing any exceptions whatsoever.  To accomplish these restrictions, you must add a throw clause to a function definition. ret-type func-name(arg-list) throw(type-list) { // ... } • only those data types contained in the comma-separated type-list may be thrown by the function. • Throwing any other type of expression will cause abnormal program termination. • If you don't want a function to be able to throw any exceptions, then use an empty list.
  • 26. #include <iostream> using namespace std; // This function can only throw ints, chars, and doubles. void fun(int test) throw(int, char, double) { if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } int main() { cout << "startn"; try { fun(0); // also, try passing 1 and 2 to fun() } catch(int i) { cout << "Caught an integern"; } catch(char c) { cout << "Caught charn"; } catch(double d) { cout << "Caught doublen"; } cout << "end"; return 0;
  • 27. UNDERSTANDING TERMINATE( ) AND UNEXPECTED( )  terminate( ) and unexpected( ) are called when something goes wrong during the exception-handling process.  These functions are supplied by the Standard C++ library.  Their prototypes are shown here:  These functions require the header <exception>.  by default, both functions halt program execution when an exception handling error occurs. void terminate( ); void unexpected( );
  • 28. UNDERSTANDING TERMINATE( ) AND UNEXPECTED( )  The terminate( ) function is called whenever the exception handling subsystem fails to find a matching catch statement for an exception.  It is also called if your program attempts to rethrow an exception when no exception was originally thrown.  For example, such a circumstance could occur when, in the process of unwinding the stack because of an exception, a destructor for an object being destroyed throws an exception.  In general, terminate( ) is the handler of last resort when no other handlers for an exception are available. By default, terminate( ) calls abort( ).  The unexpected( ) function is called when a function attempts to throw an exception that is not allowed by its throw list. By default, unexpected( ) calls terminate( ).
  • 29. THE UNCAUGHT_EXCEPTION( ) FUNCTION  The C++ exception handling subsystem supplies one other function that you may find useful: uncaught_exception( ).  Its prototype is shown here:  This function returns true if an exception has been thrown but not yet caught.  Once caught, the function returns false. bool uncaught_exception( );
  • 31. INTRODUCTION  C++ supports two complete I/O systems:  one inherited from C and  object-oriented I/O system defined by C++ (hereafter called simply the C++ I/O system).  The different aspects of C++'s I/O system, such as console I/O and disk I/O, are actually just different perspectives on the same mechanism.  the I/O system inherited from C is extremely rich, flexible, and powerful.  The C's I/O system knows nothing about objects. Therefore, for C++ to provide complete support for object-oriented programming, it was necessary to create an I/O system that could operate on user-defined objects.  In addition to support for objects, there are several benefits to using C++'s I/O system even in programs that don't make extensive (or any) use of user-defined objects.
  • 32. OLDVS. MODERN C++ I/O  There are currently two versions of the C++ object-oriented I/O library in use:  the older one that is based upon the original specifications for C++ and  the newer one defined by Standard C++.  The old I/O library is supported by the header file <iostream.h>.  The new I/O library is supported by the header <iostream>.  For the most part the two libraries appear the same to the programmer.  This is because the new I/O library is, in essence, simply an updated and improved version of the old one.  In fact, the vast majority of differences between the two occur beneath the surface, in the way that the libraries are implemented—not in how they are used.
  • 33. OLDVS. MODERN C++ I/O  From the programmer's perspective, there are two main differences between the old and new C++ I/O libraries.  First, the new I/O library contains a few additional features and defines some new data types.  Thus, the new I/O library is essentially a superset of the old one. Nearly all programs originally written for the old library will compile without substantive changes when the new library is used.  Second, the old-style I/O library was in the global namespace.  The new-style library is in the std namespace.
  • 34. C++ STREAMS  the C++ I/O system operates through streams.  A stream is a sequence of bytes.  The I/O system in c++ is designed to work with a wide variety of devices including terminals, disks, and tape drives.  Although each device is very different, the I/O system supplies an interface to the programmer that is independent of the actual device being accessed. This interface is known as stream.  A stream is a logical device that either produces or consumes information.  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.
  • 35. C++ STREAMS  In other words, a program extracts the bytes from an input stream and inserts bytes into an output stream as illustrated in Fig.
  • 36. C++ STREAMS  The data to the input stream can come from the keyboard or any other storage device.  Similarly, the data in the output stream can go to any storage devices or screen.  stream acts as an interface between the program and the I/O device. Therefore, a c++ programs handles data (input or output) independent of the devices used.  C++ language contains several pre-defined streams that are automatically opened when a program begins its execution.  These include cin and cout which have been very often in our earlier programs.  The cin operator represents the input stream connected to the standard input device (usually the keyboard) and cout operator represents the output stream connected to the standard output device (usually the screen).  Note : the keyboard and the screen are default options. We can redirect streams to the other devices or files, if necessary.
  • 37. THE C++ STREAM CLASSES  The C++ programming Input/Output(I/O) system contains a hierarchy of classes that are used to define various streams to deal with both the disk files and console.  These all classes are called stream classes.  the below figure, shows the hierarchy of the stream classes used for the input and output(I/O) operations with the console unit.  These classes are declared in the headerfile <iostream>.  This file should be included in all the programs that are communicate with the console unit.
  • 38. THE C++ STREAM CLASSES  The I/O classes begin with a system of template classes. Once a template class has been defined, specific instances of it can be created.  As it relates to the I/O library, Standard C++ creates two specializations of the I/O template classes:  one for 8-bit characters and  another for wide characters.
  • 39. THE C++ STREAM CLASSES
  • 40. THE C++ STREAM CLASSES  The I/O hierarchy shown is usually mentioned without the prefix basic_, that is, basic_ ios is usually referred to as ios. The C++ I/O system is built upon two related but different template class hierarchies.  The first is derived from the low-level I/O class called basic_streambuf. This class supplies the basic, low-level input and output operations, and provides the underlying support for the entire C++ I/O system.  The class hierarchy that you will most commonly be working with is derived from basic_ios  This is a high-level I/O class that provides formatting, error checking, and status information related to stream I/O.  ios is the base class for istream (input stream) ostream( output stream) which are, in turn, base classes for iostream (input/output stream).
  • 41. THE C++ STREAM CLASSES  The class ios(input output system) provides the basic support for formatted and unformatted I/O (Input/output)operations.  In C++ programming the class istream provides the facilities for formatted and unformatted input while the class ostream (through inheritance) gives the facilities only for formatted outputs.  In C++ class iostream provides the facilities for handling both output and input streams.  There are three classes, namely,ostream_withassign, istream_withassign, and iostream_withassign add assignment operators to these classes.
  • 42. class name Contents ios (General I/O (input output) stream class) include 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 file handling formatted input and output operations istream (input stream) Inherits the properties of ios Declares input functions such as get() , getline() and read(),Contains overload extraction operator >> ostream (output stream) Inherits the properties of ios, Declares output functions put() and write(), Contains overloaded insertion operator << iostream (input/output stream) Inherits the properties of ios stream and ostream through multiple inheritance thus contains all the input and output functions. streambuf Provides an interface to physical devices through buffers. Acts as a base for filebuf used ios files.
  • 43. THE C++ STREAM CLASSES  I/O library creates two specializations of the template class hierarchies just described: one for 8-bit characters and one for wide characters.  Here is a list of the mapping of template class names to their character and wide-character versions.
  • 44. C++'S PREDEFINED STREAMS  When a C++ program begins execution, four built-in streams are automatically opened.  They are:  Streams cin, cout, and cerr correspond to C's stdin, stdout, and stderr.  By default, the standard streams are used to communicate with the console.
  • 45. C++STREAMS There are mainly two types of console I/O operations form: 1. Formatted console input output (Formatted I/O)  bytes are grouped and converted to types such as int, double, string or user-defined types.  In Formatted IO operations are supported via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a consistent public IO interface 2. Unformatted console input output  unformatted or low-level IO, bytes are treated as raw bytes and unconverted.
  • 46. FORMATTED I/O  The C++ I/O system allows you to format I/O operations  For example, you can set a field width, specify a number base, or determine how many digits after the decimal point will be displayed.  There are two different ways that you can format data. 1. using the ios class function and flags.  Specifically, you can set various format status flags defined inside the ios class or call various ios member functions. 2. use special functions called manipulators 3. user defined output functions
  • 47. 1.FORMATTING USING THE IOS MEMBERS Formatting Flags  Each stream has associated with it a set of format flags that control the way information is formatted.  The ios class declares a bitmask enumeration called fmtflags in which the following values are defined
  • 48. 1.FORMATTING USING THE IOS MEMBERS ios::showbase Uses the base indicator on output ios::skipws flag is set, leading white-space characters (spaces, tabs, and newlines) are discarded when performing input on a stream. ios::left output is left justified. ios::right output is right justified ios::internal flag is set, a numeric value is padded to fill a field by inserting spaces between any sign or base character ios::oct output to be displayed in octal. ios::hex output to be displayed in hexadecimal ios::dec To return output to decimal, set the dec flag. ios::uppercase Uses capital cases for output. basefield adjustfield
  • 49. 1.FORMATTING USING THE IOS MEMBERS ios::scientific floating-point numeric values are displayed using scientific notation ios::fixed floating-point values are displayed using normal notation ios::unitbuf Flushes all stream after insertion ios::boolalpha is set, Booleans can be input or output using the keywords true and false. ios::showpos leading plus sign to be displayed before positive values. ios::showpoint Shows decimal point and trailing zeros floatfield.
  • 50. 1.FORMATTING USING THE IOS MEMBERS Setting the Format Flags  To set a flag, use the setf( ) function. This function is a member of ios. Its most common form is shown here: fmtflags setf(fmtflags flags);  This function returns the previous settings of the format flags and turns on those flags specified by flags  stream.setf(ios::showpos);  Here, stream is the stream you wish to affect. Notice the use of ios:: to qualify showpos.  Since showpos is an enumerated constant defined by the ios class, it must be qualified by ios when it is used.
  • 51. #include <iostream> using namespace std; int main() { cout.setf(ios::showpoint); cout.setf(ios::showpos); cout << 100.0; // displays +100.000 return 0; } +100.000 -------------------------------- Process exited after 0.3054 seconds with return value 0 Press any key to continue . . .
  • 52. 1.FORMATTING USING THE IOS MEMBERS Clearing Format Flags  The complement of setf( ) is unsetf( ).  This member function of ios is used to clear one or more format flags. Its general form is void unsetf(fmtflags flags);  The flags specified by flags are cleared. (All other flags are unaffected.)
  • 53. #include <iostream> using namespace std; int main() { cout.setf(ios::uppercase | ios::scientific); cout << 100.12; // displays 1.001200E+02 cout.unsetf(ios::uppercase); // clear uppercase cout << " n" << 100.12; // displays 1.001200e+02 return 0; } 1.001200E+002 1.001200e+002 -------------------------------- Process exited after 0.1506 seconds with return value 0 Press any key to continue . . .
  • 54. 1.FORMATTING USING THE IOS MEMBERS Formatting using ios functions  The ios class contain a large number of member functions that would help us to format the output in several ways.  The most important ones among them are listed in below Table Table: ios format functions width () To specify the required fields size for displaying an output value or contents precesion () To specify the number of digits to be displayed after the decimal point of a float value fill () To specify a characters that are used to fill the unused portion of a field setf() To specify format flags that can control the form of output display (such as left-justification and right-justification) unsetf() To clear flags specified
  • 55. 1.FORMATTING USING THE IOS MEMBERS Using width( )  Using this function, we can specify the width of a value to be displayed in the output at the console.  Its prototype is  Here, w becomes the field width, and the previous field width is returned.  The streamsize type is defined as some form of integer by the compiler.  After you set a minimum field width, when a value uses less than the specified width, the field will be padded with the current fill character (space, by default) to reach the field width.  If the size of the value exceeds the minimum field width, the field will be overrun.  No values are truncated. streamsize width(streamsize w); Ex: width(5);
  • 56. 1.FORMATTING USING THE IOS MEMBERS Using precision( )  When outputting floating-point values, you can determine the number of digits of precision by using the precision( ) function.  Its prototype is shown here:  Here the precision is set to p, and the old value is returned.The default precision is 6 streamsize precision(streamsize p);
  • 57. 1.FORMATTING USING THE IOS MEMBERS Using fill( )  By default, when a field needs to be filled, it is filled with spaces.  You can specify the fill character by using the fill( ) function.  Its prototype is :  After a call to fill( ), ch becomes the new fill character, and the old one is returned. char fill(char ch);
  • 58. #include <iostream> using namespace std; int main() { cout.precision(4) ; cout.width(10); cout << 10.12345 << "n"; // displays 10.12 cout.fill('*'); cout.width(10); cout << 10.12345 << "n"; // displays *****10.12 cout.width(10); cout << "Hi!" << "n"; // displays *******Hi! cout.width(10); cout.setf(ios::left); // left justify cout << 10.12345; // displays 10.12***** return 0; } 10.12 *****10.12 *******Hi! 10.12***** --------------------------------
  • 59. 2.USING MANIPULATORS TO FORMAT I/O  Manipulators are special functions that can be included in the I/O(Input output) statements to alter the format parameters of a stream.  As you can see by examining the table, many of the I/O manipulators parallel member functions of the ios class.  Many of the manipulators were added recently to C++ and will not be supported by older compilers.  To access manipulators that take parameters (such as setw( )), you must include <iomanip> in your program
  • 62. 2.USING MANIPULATORS TO FORMAT I/O Program that uses some manipulators program uses ios member functions to achieve the same results: #include <iostream> #include <iomanip> using namespace std; int main() { cout.setf(ios::hex, ios::basefield); cout << 100 << "n"; // 100 in hex cout.fill('?'); cout.width(10); cout << 2343.0; return 0; #include <iostream> #include <iomanip> using namespace std; int main() { cout << hex << 100 << endl; cout << setfill('?') << setw(10) << 2343.0; return 0; }
  • 63. OVERLOADING << AND >>  As you know, the << and the >> operators are overloaded in C++ to perform I/O operations on C++'s built-in types.  In the language of C++, the << output operator is referred to as the insertion operator because it inserts characters into a stream.  the >> input operator is called the extraction operator because it extracts characters from a stream.  The functions that overload the insertion and extraction operators are generally called inserters and extractors, respectively.
  • 64. OVERLOADING << AND >> CreatingYour Own Inserters  All inserter functions have this general form:  the function returns a reference to a stream of type ostream.  the first parameter to the function is a reference to the output stream.  The second parameter is the object being inserted.  The last thing the inserter must do before exiting is return stream. ostream &operator<<(ostream &stream, class_type obj) { // body of inserter return stream; }
  • 65. OVERLOADING << AND >> CreatingYour Own Extractors  Extractors are the complement of inserters.  The general form of an extractor function is  Extractors return a reference to a stream of type istream, which is an input stream.  The first parameter must also be a reference to a stream of type istream. istream &operator>>(istream &stream, class_type &obj) { // body of extractor return stream; }
  • 67. <FSTREAM> AND THE FILE CLASSES  To perform file I/O, you must include the header <fstream> in your program.  It defines several classes, including ifstream, ofstream, and fstream.  These classes are derived from istream, ostream, and iostream, respectively.  Remember, istream, ostream, and iostream are derived from ios, so ifstream, ofstream, and fstream also have access to all operations defined by ios
  • 68. <FSTREAM> AND THE FILE CLASSES
  • 69. <FSTREAM> AND THE FILE CLASSES  When working with files in C++, the following classes can be used:  ofstream: writing to a file  Ifstream: reading for a file  fstream reading/writing
  • 70. <FSTREAM> AND THE FILE CLASSES
  • 71. GENERAL FILE I/O STEPS 1. Include the header file fstream in the program. 2. Declare file stream variables. 3. Associate the file stream variables with the input/output sources. 4. Open the file 5. Use the file stream variables with >>, <<, or other input/output functions. 6. Close the file.
  • 72. OPENING & CLOSING A FILE  We can open a connection to the file in two ways: 1. one way is by using the open() function: is useful only when we use only one file in the stream. 2. second way is by using the appropriate constructor: is useful when we want to manage multiple files using one stream  This function is a member of each of the three stream classes. The prototype for each is shown here:
  • 73. OPENING & CLOSING A FILE filename is the name of the file; it can include a path specifier. The value of mode determines how the file is opened. It must be one or more of the following values defined by openmode, is an enumeration defined by ios (through its base class ios_base. void ifstream::open(const char *filename, ios::openmode mode = ios::in); void ofstream::open(const char *filename, ios::openmode mode = ios::out | ios::trunc); void fstream::open(const char *filename, ios::openmode mode = ios::in | ios::out);
  • 75. OPENING & CLOSING A FILE  The following fragment opens a normal output file.  If open( ) fails, the stream will evaluate to false when used in a Boolean expression.  Therefore, before using a file, you should test to make sure that the open operation succeeded.You can do so by using a statement like this #include <fstream> ofstream out; out.open("test", ios::out); #include <fstream> ifstream file; file.open("example.txt", std::ios::in); if(!mystream) { cout << "Cannot open file.n"; // handle error }
  • 76. OPENING & CLOSING A FILE  c++ open using constructor the ifstream, ofstream, and fstream classes have constructors that automatically open the file.  The constructors have the same parameters and defaults as the open( ) function.  To close a file, use the member function close( ).  The close( ) function takes no parameters and returns no value. ifstream mystream("myfile"); // open file for input mystream.close();
  • 77. UNFORMATTED AND BINARY I/O  While reading and writing formatted text files is very easy, it is not always the most efficient way to handle files.  Also, there will be times when you need to store unformatted (raw) binary data, not text. put( ) and get( )  To read and write unformatted data is by using the member functions get( ) and put( ). These functions operate on characters.  That is, get( ) will read a character and put( ) will write a character.  if you have opened the file for binary operations and are operating on a char then these functions read and write bytes of data. istream &get(char &ch); ostream &put(char ch);
  • 78. UNFORMATTED AND BINARY I/O:READ( ) AND WRITE( )  to read and write blocks of binary data is to use C++'s read( ) and write( ) functions. Their prototypes are  The read( ) function reads num characters from the invoking stream and puts them in the buffer pointed to by buf.  The write( ) function writes num characters to the invoking stream from the buffer pointed to by buf.  streamsize is a type defined by the C++ library as some form of integer. It is capable of holding the largest number of characters that can be transferred in any one I/O operation istream &read(char *buf, streamsize num); ostream &write(const char *buf, streamsize num);
  • 79. UNFORMATTED AND BINARY I/O:GETLINE( )  Another function that performs input is getline( ). It is a member of each input stream class.  The first form reads characters into the array pointed to by buf until either num−1 characters have been read, a newline character has been found, or the end of the file has been encountered. The array pointed to by buf will be null terminated by getline( ).If the newline character is encountered in the input stream, it is extracted, but is not put into buf.  The second form reads characters into the array pointed to by buf until either num−1 characters have been read, the character specified by delim has been found, or the end of the file has been encountered. The array pointed to by buf will be null terminated by getline( ). If the delimiter character is encountered in the input stream, it is extracted, but is not put into buf. istream &getline(char *buf, streamsize num); istream &getline(char *buf, streamsize num, char delim);
  • 80. DETECTING EOF  To detect when the end of the file is reached by using the member function eof( ), which has this prototype:  bool eof( );  It returns true when the end of the file has been reached; otherwise it returns false