0% found this document useful (0 votes)
23 views36 pages

C++ ProgrammingDay 10

The document discusses C++ streams and I/O operations. It describes the different stream classes like istream, ostream and iostream and how they handle input and output. It also explains formatted and unformatted I/O, file handling operations and exception handling in C++.

Uploaded by

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

C++ ProgrammingDay 10

The document discusses C++ streams and I/O operations. It describes the different stream classes like istream, ostream and iostream and how they handle input and output. It also explains formatted and unformatted I/O, file handling operations and exception handling in C++.

Uploaded by

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

C++ Programming

this pointer
 C++ uses a unique keyword called this to represent an object that
invokes a member function.
 this is a pointer that points to the object for which the function was
called
 This pointer is automatically passed to the member function when it
is called.

March 18, 2024 CDAC, Thiruvananthapuram 2


C++ streams
 A stream is a sequence of bytes.
 The source stream that provides data to the program is called input
stream
 The destination stream that receives output from the program is
called output stream.
 In C++, cin represents the input stream connected to the standard
input device and cout represents the output stream connected to the
output device.

March 18, 2024 CDAC, Thiruvananthapuram 3


C++ stream classes
 ios is the base class for istream(Input Stream) and ostream(Output
Stream) which are in turn base classes for iostream.
 ios class provides the basic support for formatted and unformatted
I/O operations
 istream class provides the facilities for formatted and unformatted
input while ostream class provides the facilities for formatted output .
 iostream class provides the facilities for handling both input and
output streams
 These classes are declared in the header file iostream. .

March 18, 2024 CDAC, Thiruvananthapuram 4


Unformatted I/O operations
 >> operator with cin
 << operator with cout
 The classes istream and ostream defines two member functions get()
and put() respectively to handle the single character I/O operations.
char ch;
[Link](ch);
ch=[Link]();
[Link](ch);

March 18, 2024 CDAC, Thiruvananthapuram 5


Unformatted I/O operations
 getline() function reads a whole line of text that ends with a newline
character.
[Link](line,size);
The reading is terminated as soon as either the newline character is
encountered or size-1 characters are read.
 write() function displays a line of text
[Link](line,size)
 The first argument represents the name of the string to be displayed
and the second argument indicates the number of characters to
display
March 18, 2024 CDAC, Thiruvananthapuram 6
Formatted I/O operations
 The ios class contains a large number of member functions that will
format the output
 width()
 precision()
 fill()
 setf()
 unsetf()

March 18, 2024 CDAC, Thiruvananthapuram 7


Formatted I/O operations
 width()
– width() function is used to define the width of a field necessary for the output
of an item
– [Link](w) where w is the field width
– The output will be printed in a field of w characters wide at the right end of the
field

March 18, 2024 CDAC, Thiruvananthapuram 8


Formatted I/O operations
 precision()
– precision() function is used to specify the number of digits to be displayed after
the decimal point
– [Link](d) where d is the number of digits to the right of the decimal
point
 fill()
– fill() function is used to fill the unused positions by any desired character
– [Link](ch) where ch represents the character which is used for filling the
unused positions

March 18, 2024 CDAC, Thiruvananthapuram 9


Formatted I/O operations
 setf()
– [Link](arg1,arg2) where arg1 is the formatting flags defined in the class ios
and arg2 known as the bit field specifies the group to which the formatting flag
belongs

 unsetf()
– [Link](arg1) where arg1 is the formatting flags defined in the class ios

March 18, 2024 CDAC, Thiruvananthapuram 10


Formatted I/O operations
Format Required Flag(arg1) Bit-field(arg2)
Left justified output ios::left ios::adjustfield
Right justified output ios::right ios::adjustfield
Padding after sign or base ios::internal ios::adjustfield
indicator l(like -####20)
Scientific notation ios::scientific ios::floatfield
Fixed Point notation ios::float ios::floatfield
Decimal base ios::dec ios::basefield
Octal base ios::oct ios::basefield
HexaDecimal base ios::hex ios::basefield

March 18, 2024 CDAC, Thiruvananthapuram 11


Managing output with 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

March 18, 2024 CDAC, Thiruvananthapuram 12


Managing output with Manipulators
 The most commonly used manipulators are:
– setw(int w)
• set the field width to w
– setprecision(int d)
• set the floating point precision to d
– setfill(char c)
• set the fill character to c
– setiosflags(long f)
• set the format flag f
– resetiosflags(long f) // clear the flag specified by f
March 18, 2024 CDAC, Thiruvananthapuram 13
File stream classes
 There are 3 classes for handling files
– ifstream – for handling input files
– ofstream – for handling output files
– fstream – for handling files on which both input and output can be performed
 These classes are derived from fstreambase and from classes declared
in the header file iostream.
 All these classes are declared in the header file fstream

March 18, 2024 CDAC, Thiruvananthapuram 14


Opening and Closing of files
 To process a file, the file must be opened.
 In C++, a file can be opened using the following:
– Constructor of the class
• Create a file stream object to manage the stream using the appropriate class and initialize the
file object with the desired filename.
• Eg: ofstream obj(“[Link]”)
– open() method
• open() can be used to open multiple files that use the same stream object
• filestreamclass stream_object;
• stream_object.open(“filename”)

 The files can be closed using close() function


– [Link]() where obj is the filestream object
March 18, 2024 CDAC, Thiruvananthapuram 15
End of file
 An ifstream object, returns a value of 0 if any error occurs in the file
operation including the end-of-file condition
while(fin)
 The while loop terminates when fin returns a value of zero on
reaching the end of file condition
 eof() function of ios class returns a non-zero value if the end of ile
condition is encountered and a zero otherwise
if([Link]()!=0) { …..} where fin is a file object

March 18, 2024 CDAC, Thiruvananthapuram 16


File modes
 File modes are specified as the second argument to the open()
function.
 Most commonly used file modes are
– ios :: in
• This opens the file in input mode. If the file does not exist , open() function returns
a null pointer
– ios : :out
• This opens the file in output mode. If the file does not exist , a new file will be created and if
the file exists, the file will be used after erasing the existing contents of the file
– ios :: app
• This opens the file in append mode. If the file does not exist , a new file will be created and if
the file exists, the new contents will be written from the end of file.

March 18, 2024 CDAC, Thiruvananthapuram 17


put() and get() functions
 put() function writes a single character to the associated
stream.
– [Link](character)
 get() function reads a single character from the associated
stream
– [Link](character) or character=[Link]()

March 18, 2024 CDAC, Thiruvananthapuram 18


read() and write() functions
 read() and write() functions handles the data in binary form
 Syntax of read() and write() functions are as follows
[Link]((char *) &object, sizeof(object))
[Link]((char *) &object, sizeof(object))

March 18, 2024 CDAC, Thiruvananthapuram 19


Exception Handling
 Exceptions are runtime anomalies or unusual conditions that a
program may encounter while executing.
 C++ exception handling mechanism is usually built upon 3 keywords
namely try, catch and throw.
 The keyword try is used to preface a block of statements which may
generate exceptions.

March 18, 2024 CDAC, Thiruvananthapuram 20


Exception Handling
 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 a throw statement in
the try block.
 The point at which the throw is executed is called the throw point.
 A catch block defined by the keyword catches the exception thrown
by the throw statement in the try block and handles it appropriately.
 The catch block that catches an exception must immediately follow
the try block that throws the exception.

March 18, 2024 CDAC, Thiruvananthapuram 21


Exception Handling
try
{……………
throw exception;
……….
}
catch(type arg)
{
…………
}
March 18, 2024 CDAC, Thiruvananthapuram 22
Throwing Mechanism
 When an exception that is desired to be handled is detected, it is
thrown using the throw statement in one of the following forms
– throw(exception);
– throw exception;
– throw;
 When an exception is thrown, it will be caught by the catch statement
associated with the try block.

March 18, 2024 CDAC, Thiruvananthapuram 23


Throwing Mechanism
 When an exception that is desired to be handled is detected, it is
thrown using the throw statement in one of the following forms
– throw(exception);
– throw exception;
– throw;
 When an exception is thrown, it will be caught by the catch statement
associated with the try block.

March 18, 2024 CDAC, Thiruvananthapuram 24


Catching Mechanism
 catch(type arg)
{ //statements for managing exceptions
}
 The type indicates the type of exception that catch block handles.

March 18, 2024 CDAC, Thiruvananthapuram 25


Multiple Catch Statements
 We can associate more than one catch statement with a try statement.
try{ // try block }
catch(type1 arg){ //catch block}
catch(type2 arg){ //catch block}
……………
catch(typen arg){ //catch block}

March 18, 2024 CDAC, Thiruvananthapuram 26


Multiple Catch Statements
 When an exception is thrown, the exception handlers are searched in
order for an appropriate match.
 The first handler that yields a match is executed.
 After executing the handler, the control goes to the first statement
after the last catch block for that try.
 When no match is found, the program is terminated.

March 18, 2024 CDAC, Thiruvananthapuram 27


Catch All Exceptions
 To define a catch statement to catch all exceptions instead of a certain
type, the catch statement should be defined as follows:
catch(…)
{
//Statements for processing all exceptions
}

March 18, 2024 CDAC, Thiruvananthapuram 28


Rethrowing an Exception
 A handler may decide to rethrow the exception caught without
processing it.
 For such cases, throw is called without any arguments as shown below
throw;
 This causes the current exception to be thrown to the next enclosing
try/catch sequence and is caught by a catch statement listed after that
enclosing try block.

March 18, 2024 CDAC, Thiruvananthapuram 29


Specifying Exceptions
 A function can be restricted to throw only certain exceptions by
adding a throw list clause to the function definition.
type function(arg-list) throw (type-list)
{ //function body }
 The type-list specifies the type of exceptions that may be thrown.
 Throwing any other type of exception will cause abnormal program
termination.

March 18, 2024 CDAC, Thiruvananthapuram 30


Templates
 Templates enable to define generic classes and functions and thus
provides support for Generic Programming
 Generic Programming is an approach where generic types are used as
parameters so that they can work for a variety of suitable data types
and data structures

March 18, 2024 CDAC, Thiruvananthapuram 31


Class Templates
template<class T>
class classname
{ …….. //body of the class };
 The template keyword in the class definition tells the compiler that a template is
being declared and use T as a typename in the declaration.
 We can use the generic type for declaring instance variables and in member
functions
 While creating objects of class templates we have to pass the appropriate data type
classname< datatype> object;
This data type will be substituted for the generic type T

March 18, 2024 CDAC, Thiruvananthapuram 32


Class Templates with Multiple Parameters
template<class T1,class T2>
class classname
{
…….. //body of the class
};

Objects of such class templates are created as


classname< datatype1,datatype2> object;

March 18, 2024 CDAC, Thiruvananthapuram 33


Function Templates
 Function templates can also be used to create a family of functions with different
argument types
template<class T>
returntype functionname(arguments of type T)
{ …….. //body of the function };

 The function template syntax is similar to that of the class template except that we
are defining functions instead of classes.

March 18, 2024 CDAC, Thiruvananthapuram 34


Function Templates with Multiple Parameters
template<class T1,class T2>
returntype functionname(arguments of type T1,T2)
{ …….. //body of the function };

March 18, 2024 CDAC, Thiruvananthapuram 35


Function and Function templates
 If a program has both the function and function template
with the same name, first, the compiler selects the normal
function, if it matches with the requested data type,
otherwise, it creates a function using the function template.

March 18, 2024 CDAC, Thiruvananthapuram 36

You might also like