SlideShare a Scribd company logo
UNIT III
C++ PROGRAMMING ADVANCED FEATURES
Abstract class – Exception handling –
Standard libraries – Generic Programming
– templates – class template – function
template – STL – containers – iterators –
function adaptors – allocators –
Parameterizing the class – File handling
concepts.
ABSTRACT CLASS
• Abstract class is a class which contains atleast
one pure virtual function in it.
• Abstract class are used to provide an interface
for its sub classes.
• Abstract class cannot be instantiated to create
objects.
• Abstract class can have normal functions and
variables along with a pure virtual function.
Class Abstractclass
{
public :
virtual void func( ) = 0;
};
#include<iostream>
using namespace std;
class AbstractBase
{
public :
virtual void display( ) = 0;
};
class Derived:public
AbstractBase
{
public:
void display( )
{
cout <<“ virtual function
implemented in Derived
class”;
}
};
int main( )
{
AbstractBase *AB;
Derived d;
AB = &d;
AB -> display( );
return 0;
}
EXCEPTION HANDLING
• Compile Time Errors - Errors caught during
compile time
• Run Time Errors – Errors caught during run
time
EXCEPTION HANDLING
• An exception is a situation in which a program
has an unexpected circumstance during pro-
gram execution.
• Exceptions are caused by errors, invalid inputs
or invalid processing which can lead to either
program termination or generating
unexpected outputs.
• All errors are exceptions but not necessarily all
exceptions are errors.
• Exception handling is a mechanism that separates
code that detects and handles exceptional
circumstances from the rest of the program.
• Exception handling can resolve exceptions by
allowing a program to continue executing or by
notifying the user about that problem and
terminate the program in a controlled manner.
• Elements
– Try block
– Catch blocks
– throw expressions
– Exception specifications
• Try block
– identifies a block of code for which particular
exceptions will be activated.
– This is done using a “try” keyword
– It is followed by one or more catch blocks
• Catch block
– catches an exception with an exception handler at
the place required to handle the problem
– This is done using a “catch” keyword
• Syntax
try
{
statements
}
catch (datatype argument)
{
exception handing code
}
:
:
catch (datatype argument)
{
exception handing code
}
• If no exception is thrown in a try block then all
catch blocks for that try block are ignored and
the execution resumes after the last catch
block.
• If an exception is thrown in a try block then
the remaining statements in that try block are
ignored.
• If exception matches the parameter type in
one of the catch blocks, then the code of that
catch block executes and ignores the
remaining catch block
• Throw block
– program throws an exception when a problem is
detected in a try block.
– This is done using “throw” keyword
Syntax:
• throw (exception);
• throw exception ;
• throw;
• Exception Specifications
– Exception specifications are used to provide
summary information about the type of
exceptions
#include<iostream>
using namespace std;
int main( )
{
int dividend, divisor, quotient;
try
{
cin >> dividend;
cin >> divisor ;
if (divisor==0)
throw divisor ;
else if (divisor<0)
throw string(“negative integer”);
quotient = dividend / divisor ;
cout << "Quotient = "<< quotient;
}
catch (int)
{
cout << “Division by zero” ;
}
Output:
5
0
Division by zero
5
3
Quotient = 1
#include<iostream>
using namespace std;
int main( )
{
int dividend, divisor, quotient;
try
{
cin >> dividend;
cin >> divisor ;
if (divisor==0)
throw divisor ;
else if (divisor<0)
throw string(“negative
integer”);
quotient = dividend /
divisor ;
cout << "Quotient = "<<
quotient;
}
catch (int)
{
cout<<"Division by zero" ;
}
catch (string s)
{
cout << s << endl;
}
return 0;
}
• Output:
5
0
Division by zero
5
-3
negative integer
5
3
Quotient = 1
STANDARD LIBRARIES
• C++ Standard Library is a collection
of classes and functions
• The C++ Standard Library also incorporates most
headers of the C standard library ending with ".h“
• The C++ standard library is classified into two
parts
• Standard Function Library
– consists of general - purpose and stand - alone
functions that are not part of any class.
– perform essential services such as input and output
– library is inherited from C
• Object Oriented Class Library
– consists of a collection of classes and associated
functions
– provide support for a number of common
activities, including I/O, strings and numeric
processing.
• The standard C++ Library includes
– The language support library
– The Diagonstics Library
– The General Utilities Library
– The Standard String Template
– Localization Classes and Templates
– The Standard Template Library
– The Standard Numerics Library
– The Standard Input/Output Library
– C++ Header for the standard C library
• The langauge support library
• The language support library defines types
and functions that will be used implicitly by
C++ programs that employ features as new
and delete operators, exceptions handling
The Diagnostics Library
• The diagnostics library is used to detect and
report error conditions in C++ programs.
• The Standard String Templates
The string library is a facility for the
manipulation of character sequences.
Localization Classes and Templates
• The localization library permits a C++ program
to address the cultural differences of its
various users.
• The Standard Template Library
• The standard template library (STL) contains
the collection of generic classes and functions
that could extend support for generic
programming. STL includes containers,
iterators and Algorithms libraries.
GENERIC PROGRAMMING
• Generic program is an abstract and an
efficient way of designing and assembling
component and interfacing them with
algorithms.
Guidelines
• Avoid polymorphism
• Use inheritance – limited
• Parameterize the procedures by the types of
their inputs
Int multiply(int x, int y)
{
return (x * y);
}
• This code works well for integer
• To multiply two floating point numbers – need
separate function.
• generic class called template can solve this
issue.
template <class T>
T multiply(T x, T y)
{
return (x * y);
}
TEMPLATES
• Foundation of generic programming
• Writing code that is independent of any particular type
• Focused on algorithms rather than single data types.
• Templates are useful for implementing generic
constructs like vectors, stacks, lists, queues, maps etc.
• Templates provide a way to reuse source code
• Types of templates:
– Class templates
– Function templates.
How Do Templates Work?
• Templates are expanded at compiler time.
• This is like macros.
• The idea is simple, source code contains only
function/class, but compiled code may contain
multiple copies of the same function/class.
Function template
• write a generic function that can be used for
different data types
• Examples of function templates are sort(),
max(), min()
• Generic functions use the concept of a function
template.
• Generic functions define a set of operations that can
be applied to the various types of data.
• The type of the data that the function will operate on
depends on the type of the data passed as a
parameter.
• For example, Quick sorting algorithm is implemented
using a generic function, it can be implemented to an
array of integers or array of floats.
• A Generic function is created by using the keyword
template.
• The template defines what function will do.
Syntax
template < class Ttype>
ret_type func_name(parameter_list)
{
// body of function.
}
#include <iostream>
template <typename T>
T myMax(T x, T y)
{
return (x > y) ? x : y;
}
void main()
{
cout << myMax<int>(3, 7);
cout << myMax<double>(3.0, 7.0);
}
Output:
7
7.0
Class Template
• Class templates are useful when a class
defines something that is independent of the
data type.
• Use class templates to create a single class to
work with different data types.
Syntax for declaring a class template:
template <class Type>
class classname
{
-----
-----
-----
}
#include <iostream>
template <class T>
class Number
{
private:
T num;
public:
Number(T n)
{
num=n;
}
T getNum()
{
return num;
}
};
void main()
{
Number<int> ob1(7);
Number<double> ob2(7.7);
cout << "int Number = " <<
ob1.getNum();
cout << "double Number = "
<< ob2.getNum() ;
}
STANDARD TEMPLATE LIBRARY (STL)
• In C++, Standard Template Library defines
template based and reusable components.
• It provides a set of well structured generic C++
templatized functions and classes.
• The basic components of standard template
library are :
1) Containers
2) Algorithms
3) Iterator
Containers
• Container are used for storing collections of
related objects
• Types
– Sequence containers
– Associative containers
– Container Adaptors
Sequence Containers
• The sequence containers implement, data
structures which can be accessed sequentially.
Container Description
array static contiguous array
vector dynamic contiguous array
deque double ended queues
List linked list
Associative containers
• Associate containers are keys to store and retrive
elements
• An associate container is non - sequential
Container Description
set The item stored act as key, no
duplicates.
multiset set allowing duplicate items.
map seperate key and value, no
duplicates
multimap map allowing duplicates keys
Container Adaptors
• Container adaptors provide a different
interface for sequential containers.
• The function push and pop are common to all
container adapters.
Containers Description
Stack -Last in first out data structure.
Queue -First in first out data structure
Priority Queue -The elements with the highest
priority are removed.
Example - stack container
#include<iostream.h>
#include<stack.h>
#include<string.h>
void main ( )
{
stack allwords;
string word;
while (cin >> word)
{
allwords.push(word);
}
cout << “Number of words = “ <<
allwords.size( );
while (!allwords.empty ( ))
{
cout << allwords.top ( );
allwords.pop ( );
}
}
o/p
World
Welcome
Number of words = 2
welcome
world
Iterators
• Iterators are pointers like entities that are used to
access individual elements in a container.
• Iterators are used to move sequentially element by
element to the container.
Iterators Description
Input can read from them
Output can write to them
Forward Forward iterators are limited to one
direction.
Bidirectional can be iterated in both direction in
forward and backward
Randomaccess It is bidirectional and provides the
functionality as pointers.
Operations of iterators :-
1. begin() :- This function is used to return
the beginning position of the container.
2. end() :- This function is used to return
the after end position of the container.
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
vector<int>::iterator ptr;
cout << "The vector elements are : ";
for (ptr = ar.begin(); ptr < ar.end();
ptr++)
cout << *ptr << " ";
return 0;
}
The vector elements
are : 1 2 3 4 5
STL Function Adapters
• STL has predefined functor adapters that will
change their functors so that they can:
– Perform function composition & binding
– Allow fewer created functors
Functors
• A functor (or function object) is a C++ class that acts like a function.
• Functors are called using the same old function call syntax.
• This is made possible by overloading the () operator
class Greet {
public:
void operator()() {
// function body
}
};
// create an instance of Greet
Greet greet;
// call the object as a function
greet();
Function Adaptors
A function adaptor also be used to alter the
behavior of a function or function object
There are three types of STL function
adapters
* Binders (bind1st(), bind2nd(), & bind())
bind one of their arguments
* Negators ((not1, not2, & not_fn) adapt
functors by negating arguments)
* Member functions
Binder Function Adaptor
• A binder takes a two-argument function, and
binds either the first or second argument to a
specific value, thereby yielding a one-
argument function.
• Function objects that take two arguments are
called binary function objects.
• Binary function objects are required to include
typedefs first_argument_type, second_argum
ent_type, and result_type.
• (bind1st(), bind2nd(), & bind()) bind one of
their arguments
• binder1st binds the value to the first
argument of the binary function,
and binder2nd does the same thing for the
second argument of the function.
• A binder can be used to transform a binary
function object into an unary function object by
acting as a converter between the function object
and an algorithm.
• The header <algorithm> defines a collection of
functions especially designed to be used on
ranges of elements.
count_if() is used to get the number of elements
in a specified range which satisfy a condition.
Syntax:
count_if(start, end, condition);
#include<iostream>
#include<iterator>
#include<algorithm>
int main( )
{
int arr[ ] = {1, 2, 3, 4, 5};
int s;
s=count_if(arr, arr+5, bind1st(not_equal_to(), 5));
cout<<<s<< “ elements that are not equal to 5”;
}
Output
4 elements that are not equal to 5
Negator Function Adaptor
• The negator function adaptor can be used to
store the opposite result of a function object
• Negators (not1, not2, & not_fn) adapt
functors by negating arguments
• The negators not1() and not2() take a unary
and a binary predicate function object,
respectively, and create a new function object
that yields the complement of the original.
#include<iostream>
#include<iterator>
#include<algorithm>
int main( )
{
int Arr[ ] = {6, 7, 8, 9, 10};
cout<<count_if(Arr,
Arr+5,not1(bind2nd(greater_equal<int>( ), 8)));
}
Output
2
Member Function Adaptor
• Member function adaptor can be used to
allow class member functions or C-style
functions as arguments to STL predefined
algorithms.
• Member functions (ptr_fun, mem_fun, &
mem_fn) allow functors to be class members
Allocators
• Allocators are classes that define memory
models to be used by STL containers.
• Functions performed by allocators are:
– Allocate
– Deallocate
– Construct
– Destroy
#include<iostream>
#include<memory>
#include<string>
void main( )
{
std::allocator a1;
int* a = a1.allocate(10);
a[9] = 101;
std::cout << a[9];
a1.deallocate(a, 10); std::allocator_traits<decltype(a1)::rebind_alloc<std::string> a2;
std::string* s = a2.allocate(2);
a2.construct(s, “Welcome”);
a2.construct(s + 1, “World”);
std::cout << s[0] << ‘ ‘ << s[1];
a2.destroy(s);
a2.destroy(s + 1);
a2.deallocates(s, 2);
}
PARAMETERIZING THE CLASS
• Parameterizing classes specify parameters
that must be defined by any binding class.
• In C++, parameterized class is referred as class
templates.
#include <iostream>
template <class T>
class Number
{
private:
T num;
public:
Number(T n)
{
num=n
}
T getNum()
{
return num;
}
};
void main()
{
Number<int> ob1(7);
cout << "int Number = " << ob1.getNum();
}
FILE HANDLING
• C++ I/O system operates on streams
• A stream is a flow of characters.
• A stream is a common, logical interface to
various devices of a computer system
• An input stream is a flow of characters into
the program.
• An output stream is a flow of characters out of
the program.
• Types of streams: text and binary
• Text streams contain printable characters and
control characters that are organized into lines.
Each line consists of zero or more characters and
ends with a new-line character ( n ).
• A binary stream consists of one or more bytes of
arbitrary information.
• The I/O system of C++ has many classes and file
handling functions.
• All these classes are derived from the base class
ios.
The hierarchy of C++ I/O classes
• ios class is topmost class in the stream classes
hierarchy. It is the base class for istream,
ostream, and streambuf class.
• istream and ostream serves the base classes
for iostream class. The class istream is used
for input and ostream for the output.
• The _withassign classes are provided with
extra functionality for the assignment
operations
Facilities provided by these stream classes.
• The ios class: The ios class is responsible for
providing all input and output facilities to all
other stream classes.
The istream class: This class is responsible for
handling input stream. It provides number of
function for handling chars, strings and
objects such as get, getline, read, ignore,
putback etc.
#include <iostream>
using namespace std;
int main()
{
char x;
// used to scan a single char
cin.get(x);
cout << x;
}
• The ostream class: This class is responsible for
handling output stream. It provides number of
function for handling chars, strings and
objects such as write, put etc..
#include <iostream>
using namespace std;
int main()
{
char x;
// used to scan a single char
cin.get(x);
// used to put a single char onto the screen.
cout.put(x);
}
The iostream: This class is responsible for handling both input
and output stream as both istream class and ostream class is
inherited into it. It provides function of both istream class and
ostream class for handling chars, strings and objects such as get,
getline, read, ignore, putback, put, write etc..
#include <iostream>
using namespace std;
int main()
{
// this function display
// ncount character from array
cout.write("geeksforgeeks", 5);
}
File I/O
• To perform file I/O, you must include<fstream> in
program.
• It defines several classes, including ifstream, ofstream
and fstream.
• These classes are derived from ios.
• ofstream - represents the output file stream and is
used to create files and to write information to files.
• ifstream - represents the input file stream and is used
to read information from files.
• fstream - This data type represents the file stream
generally, and has the capabilities of both ofstream and
ifstream
Sequential Input and Output
Operations
• Sequential input and output operations are
performed on sequential files
• In C++ every sequential file will be associated
with two file pointers.
• get() - input pointer, it is used to read the
content of the file
• put()-output pointer, it is used to write
content to the file
To write content to
the file
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char c,fname[10];
clrscr();
cout<<"Enter file name:";
cin>>fname;
ifstream in(fname);
if(!in)
{
cout<<"File Does not Exist";
getch();
return;
}
cout<<"nn";
while(in.eof()==0)
{
in.get(c);
cout<<c;
}
getch();
}
WRITING THE
CONTENT TO THE
FILE
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char c,fname[10];
ofstream out;
cout<<"Enter File name:";
cin>>fname;
out.open(fname);
cout<<"Enter contents to store in file (Enter # at end):n";
while((c=getchar())!='#')
{
out<<c;
}
out.close();
getch();
}
Random Access Files
• Random access file is one that allows accessing
records randomly in any order.
• To perform random access to a file C++ supports
the following functions in addition to get() and
put() pointers
seekg() - Moves get pointer to specified position
seekp() -Moves put pointer to specified position
tellg() - Returns the position of get pointer
tellp() - Returns the position of get pointer
Binary File I/O
• binary file stores the content in binary format
• read( ) - function reads ‘num’ bytes
• write( ) - function writes ‘num’ bytes
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream out;
out.open(“number”,ios::binary);
int k=55;
out.write((char *)&k,sizeof(k));
out.close();
}

More Related Content

Similar to c++ Unit III - PPT.pptx

Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
Steve Johnson
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
an introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptan introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.ppt
Abdullah Yousafzai
 
Java
JavaJava
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
FarazKhan89093
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
Muhammad Abdullah
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
Woxa Technologies
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
Adeel Hamid
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
Woxa Technologies
 
Net framework
Net frameworkNet framework
Net framework
Abhishek Mukherjee
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
MZGINBarwary
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Tobias Coetzee
 
Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 

Similar to c++ Unit III - PPT.pptx (20)

Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
an introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptan introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.ppt
 
Java
JavaJava
Java
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Net framework
Net frameworkNet framework
Net framework
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
Unit iii
Unit iiiUnit iii
Unit iii
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

More from Kongunadu College of Engineering and Technology

Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
Unit - 2.ppt
Unit - 2.pptUnit - 2.ppt
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
U1.ppt
U1.pptU1.ppt
U2.ppt
U2.pptU2.ppt
U4.ppt
U4.pptU4.ppt
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U3.pptx
U3.pptxU3.pptx

More from Kongunadu College of Engineering and Technology (18)

Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptx
 
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
Unit - 1.ppt
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Unit - 2.ppt
Unit - 2.pptUnit - 2.ppt
Unit - 2.ppt
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
U1.ppt
U1.pptU1.ppt
U1.ppt
 
U2.ppt
U2.pptU2.ppt
U2.ppt
 
U4.ppt
U4.pptU4.ppt
U4.ppt
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U3.pptx
U3.pptxU3.pptx
U3.pptx
 

Recently uploaded

2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
PuktoonEngr
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
PauloRodrigues104553
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
Madhumitha Jayaram
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 

Recently uploaded (20)

2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 

c++ Unit III - PPT.pptx

  • 1. UNIT III C++ PROGRAMMING ADVANCED FEATURES Abstract class – Exception handling – Standard libraries – Generic Programming – templates – class template – function template – STL – containers – iterators – function adaptors – allocators – Parameterizing the class – File handling concepts.
  • 2. ABSTRACT CLASS • Abstract class is a class which contains atleast one pure virtual function in it. • Abstract class are used to provide an interface for its sub classes. • Abstract class cannot be instantiated to create objects. • Abstract class can have normal functions and variables along with a pure virtual function.
  • 4. #include<iostream> using namespace std; class AbstractBase { public : virtual void display( ) = 0; }; class Derived:public AbstractBase { public: void display( ) { cout <<“ virtual function implemented in Derived class”; } }; int main( ) { AbstractBase *AB; Derived d; AB = &d; AB -> display( ); return 0; }
  • 5. EXCEPTION HANDLING • Compile Time Errors - Errors caught during compile time • Run Time Errors – Errors caught during run time
  • 6. EXCEPTION HANDLING • An exception is a situation in which a program has an unexpected circumstance during pro- gram execution. • Exceptions are caused by errors, invalid inputs or invalid processing which can lead to either program termination or generating unexpected outputs. • All errors are exceptions but not necessarily all exceptions are errors.
  • 7. • Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of the program. • Exception handling can resolve exceptions by allowing a program to continue executing or by notifying the user about that problem and terminate the program in a controlled manner. • Elements – Try block – Catch blocks – throw expressions – Exception specifications
  • 8. • Try block – identifies a block of code for which particular exceptions will be activated. – This is done using a “try” keyword – It is followed by one or more catch blocks • Catch block – catches an exception with an exception handler at the place required to handle the problem – This is done using a “catch” keyword
  • 9. • Syntax try { statements } catch (datatype argument) { exception handing code } : : catch (datatype argument) { exception handing code }
  • 10. • If no exception is thrown in a try block then all catch blocks for that try block are ignored and the execution resumes after the last catch block. • If an exception is thrown in a try block then the remaining statements in that try block are ignored. • If exception matches the parameter type in one of the catch blocks, then the code of that catch block executes and ignores the remaining catch block
  • 11. • Throw block – program throws an exception when a problem is detected in a try block. – This is done using “throw” keyword Syntax: • throw (exception); • throw exception ; • throw;
  • 12.
  • 13. • Exception Specifications – Exception specifications are used to provide summary information about the type of exceptions
  • 14.
  • 15. #include<iostream> using namespace std; int main( ) { int dividend, divisor, quotient; try { cin >> dividend; cin >> divisor ; if (divisor==0) throw divisor ; else if (divisor<0) throw string(“negative integer”); quotient = dividend / divisor ; cout << "Quotient = "<< quotient; } catch (int) { cout << “Division by zero” ; } Output: 5 0 Division by zero 5 3 Quotient = 1
  • 16. #include<iostream> using namespace std; int main( ) { int dividend, divisor, quotient; try { cin >> dividend; cin >> divisor ; if (divisor==0) throw divisor ; else if (divisor<0) throw string(“negative integer”); quotient = dividend / divisor ; cout << "Quotient = "<< quotient; } catch (int) { cout<<"Division by zero" ; } catch (string s) { cout << s << endl; } return 0; }
  • 17. • Output: 5 0 Division by zero 5 -3 negative integer 5 3 Quotient = 1
  • 18. STANDARD LIBRARIES • C++ Standard Library is a collection of classes and functions • The C++ Standard Library also incorporates most headers of the C standard library ending with ".h“ • The C++ standard library is classified into two parts • Standard Function Library – consists of general - purpose and stand - alone functions that are not part of any class. – perform essential services such as input and output – library is inherited from C
  • 19. • Object Oriented Class Library – consists of a collection of classes and associated functions – provide support for a number of common activities, including I/O, strings and numeric processing.
  • 20. • The standard C++ Library includes – The language support library – The Diagonstics Library – The General Utilities Library – The Standard String Template – Localization Classes and Templates – The Standard Template Library – The Standard Numerics Library – The Standard Input/Output Library – C++ Header for the standard C library
  • 21. • The langauge support library • The language support library defines types and functions that will be used implicitly by C++ programs that employ features as new and delete operators, exceptions handling
  • 22. The Diagnostics Library • The diagnostics library is used to detect and report error conditions in C++ programs.
  • 23. • The Standard String Templates The string library is a facility for the manipulation of character sequences.
  • 24. Localization Classes and Templates • The localization library permits a C++ program to address the cultural differences of its various users.
  • 25. • The Standard Template Library • The standard template library (STL) contains the collection of generic classes and functions that could extend support for generic programming. STL includes containers, iterators and Algorithms libraries.
  • 26.
  • 27. GENERIC PROGRAMMING • Generic program is an abstract and an efficient way of designing and assembling component and interfacing them with algorithms.
  • 28. Guidelines • Avoid polymorphism • Use inheritance – limited • Parameterize the procedures by the types of their inputs
  • 29. Int multiply(int x, int y) { return (x * y); } • This code works well for integer • To multiply two floating point numbers – need separate function. • generic class called template can solve this issue.
  • 30. template <class T> T multiply(T x, T y) { return (x * y); }
  • 31. TEMPLATES • Foundation of generic programming • Writing code that is independent of any particular type • Focused on algorithms rather than single data types. • Templates are useful for implementing generic constructs like vectors, stacks, lists, queues, maps etc. • Templates provide a way to reuse source code • Types of templates: – Class templates – Function templates.
  • 32. How Do Templates Work? • Templates are expanded at compiler time. • This is like macros. • The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class.
  • 33. Function template • write a generic function that can be used for different data types • Examples of function templates are sort(), max(), min()
  • 34. • Generic functions use the concept of a function template. • Generic functions define a set of operations that can be applied to the various types of data. • The type of the data that the function will operate on depends on the type of the data passed as a parameter. • For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats. • A Generic function is created by using the keyword template. • The template defines what function will do.
  • 35. Syntax template < class Ttype> ret_type func_name(parameter_list) { // body of function. }
  • 36. #include <iostream> template <typename T> T myMax(T x, T y) { return (x > y) ? x : y; } void main() { cout << myMax<int>(3, 7); cout << myMax<double>(3.0, 7.0); } Output: 7 7.0
  • 37.
  • 38. Class Template • Class templates are useful when a class defines something that is independent of the data type. • Use class templates to create a single class to work with different data types.
  • 39. Syntax for declaring a class template: template <class Type> class classname { ----- ----- ----- }
  • 40. #include <iostream> template <class T> class Number { private: T num; public: Number(T n) { num=n; } T getNum() { return num; } }; void main() { Number<int> ob1(7); Number<double> ob2(7.7); cout << "int Number = " << ob1.getNum(); cout << "double Number = " << ob2.getNum() ; }
  • 41. STANDARD TEMPLATE LIBRARY (STL) • In C++, Standard Template Library defines template based and reusable components. • It provides a set of well structured generic C++ templatized functions and classes. • The basic components of standard template library are : 1) Containers 2) Algorithms 3) Iterator
  • 42. Containers • Container are used for storing collections of related objects • Types – Sequence containers – Associative containers – Container Adaptors
  • 43. Sequence Containers • The sequence containers implement, data structures which can be accessed sequentially. Container Description array static contiguous array vector dynamic contiguous array deque double ended queues List linked list
  • 44. Associative containers • Associate containers are keys to store and retrive elements • An associate container is non - sequential Container Description set The item stored act as key, no duplicates. multiset set allowing duplicate items. map seperate key and value, no duplicates multimap map allowing duplicates keys
  • 45. Container Adaptors • Container adaptors provide a different interface for sequential containers. • The function push and pop are common to all container adapters. Containers Description Stack -Last in first out data structure. Queue -First in first out data structure Priority Queue -The elements with the highest priority are removed.
  • 46. Example - stack container #include<iostream.h> #include<stack.h> #include<string.h> void main ( ) { stack allwords; string word; while (cin >> word) { allwords.push(word); } cout << “Number of words = “ << allwords.size( ); while (!allwords.empty ( )) { cout << allwords.top ( ); allwords.pop ( ); } } o/p World Welcome Number of words = 2 welcome world
  • 47. Iterators • Iterators are pointers like entities that are used to access individual elements in a container. • Iterators are used to move sequentially element by element to the container. Iterators Description Input can read from them Output can write to them Forward Forward iterators are limited to one direction. Bidirectional can be iterated in both direction in forward and backward Randomaccess It is bidirectional and provides the functionality as pointers.
  • 48. Operations of iterators :- 1. begin() :- This function is used to return the beginning position of the container. 2. end() :- This function is used to return the after end position of the container.
  • 49. #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; vector<int>::iterator ptr; cout << "The vector elements are : "; for (ptr = ar.begin(); ptr < ar.end(); ptr++) cout << *ptr << " "; return 0; } The vector elements are : 1 2 3 4 5
  • 50. STL Function Adapters • STL has predefined functor adapters that will change their functors so that they can: – Perform function composition & binding – Allow fewer created functors
  • 51. Functors • A functor (or function object) is a C++ class that acts like a function. • Functors are called using the same old function call syntax. • This is made possible by overloading the () operator class Greet { public: void operator()() { // function body } }; // create an instance of Greet Greet greet; // call the object as a function greet();
  • 52. Function Adaptors A function adaptor also be used to alter the behavior of a function or function object There are three types of STL function adapters * Binders (bind1st(), bind2nd(), & bind()) bind one of their arguments * Negators ((not1, not2, & not_fn) adapt functors by negating arguments) * Member functions
  • 53. Binder Function Adaptor • A binder takes a two-argument function, and binds either the first or second argument to a specific value, thereby yielding a one- argument function. • Function objects that take two arguments are called binary function objects. • Binary function objects are required to include typedefs first_argument_type, second_argum ent_type, and result_type.
  • 54. • (bind1st(), bind2nd(), & bind()) bind one of their arguments • binder1st binds the value to the first argument of the binary function, and binder2nd does the same thing for the second argument of the function.
  • 55. • A binder can be used to transform a binary function object into an unary function object by acting as a converter between the function object and an algorithm. • The header <algorithm> defines a collection of functions especially designed to be used on ranges of elements. count_if() is used to get the number of elements in a specified range which satisfy a condition. Syntax: count_if(start, end, condition);
  • 56. #include<iostream> #include<iterator> #include<algorithm> int main( ) { int arr[ ] = {1, 2, 3, 4, 5}; int s; s=count_if(arr, arr+5, bind1st(not_equal_to(), 5)); cout<<<s<< “ elements that are not equal to 5”; } Output 4 elements that are not equal to 5
  • 57. Negator Function Adaptor • The negator function adaptor can be used to store the opposite result of a function object • Negators (not1, not2, & not_fn) adapt functors by negating arguments • The negators not1() and not2() take a unary and a binary predicate function object, respectively, and create a new function object that yields the complement of the original.
  • 58. #include<iostream> #include<iterator> #include<algorithm> int main( ) { int Arr[ ] = {6, 7, 8, 9, 10}; cout<<count_if(Arr, Arr+5,not1(bind2nd(greater_equal<int>( ), 8))); } Output 2
  • 59. Member Function Adaptor • Member function adaptor can be used to allow class member functions or C-style functions as arguments to STL predefined algorithms. • Member functions (ptr_fun, mem_fun, & mem_fn) allow functors to be class members
  • 60.
  • 61. Allocators • Allocators are classes that define memory models to be used by STL containers. • Functions performed by allocators are: – Allocate – Deallocate – Construct – Destroy
  • 62. #include<iostream> #include<memory> #include<string> void main( ) { std::allocator a1; int* a = a1.allocate(10); a[9] = 101; std::cout << a[9]; a1.deallocate(a, 10); std::allocator_traits<decltype(a1)::rebind_alloc<std::string> a2; std::string* s = a2.allocate(2); a2.construct(s, “Welcome”); a2.construct(s + 1, “World”); std::cout << s[0] << ‘ ‘ << s[1]; a2.destroy(s); a2.destroy(s + 1); a2.deallocates(s, 2); }
  • 63. PARAMETERIZING THE CLASS • Parameterizing classes specify parameters that must be defined by any binding class. • In C++, parameterized class is referred as class templates.
  • 64. #include <iostream> template <class T> class Number { private: T num; public: Number(T n) { num=n } T getNum() { return num; } }; void main() { Number<int> ob1(7); cout << "int Number = " << ob1.getNum(); }
  • 65. FILE HANDLING • C++ I/O system operates on streams • A stream is a flow of characters. • A stream is a common, logical interface to various devices of a computer system • An input stream is a flow of characters into the program. • An output stream is a flow of characters out of the program.
  • 66. • Types of streams: text and binary • Text streams contain printable characters and control characters that are organized into lines. Each line consists of zero or more characters and ends with a new-line character ( n ). • A binary stream consists of one or more bytes of arbitrary information. • The I/O system of C++ has many classes and file handling functions. • All these classes are derived from the base class ios.
  • 67. The hierarchy of C++ I/O classes
  • 68. • ios class is topmost class in the stream classes hierarchy. It is the base class for istream, ostream, and streambuf class. • istream and ostream serves the base classes for iostream class. The class istream is used for input and ostream for the output. • The _withassign classes are provided with extra functionality for the assignment operations
  • 69. Facilities provided by these stream classes. • The ios class: The ios class is responsible for providing all input and output facilities to all other stream classes. The istream class: This class is responsible for handling input stream. It provides number of function for handling chars, strings and objects such as get, getline, read, ignore, putback etc.
  • 70. #include <iostream> using namespace std; int main() { char x; // used to scan a single char cin.get(x); cout << x; }
  • 71. • The ostream class: This class is responsible for handling output stream. It provides number of function for handling chars, strings and objects such as write, put etc.. #include <iostream> using namespace std; int main() { char x; // used to scan a single char cin.get(x); // used to put a single char onto the screen. cout.put(x); }
  • 72. The iostream: This class is responsible for handling both input and output stream as both istream class and ostream class is inherited into it. It provides function of both istream class and ostream class for handling chars, strings and objects such as get, getline, read, ignore, putback, put, write etc.. #include <iostream> using namespace std; int main() { // this function display // ncount character from array cout.write("geeksforgeeks", 5); }
  • 73. File I/O • To perform file I/O, you must include<fstream> in program. • It defines several classes, including ifstream, ofstream and fstream. • These classes are derived from ios. • ofstream - represents the output file stream and is used to create files and to write information to files. • ifstream - represents the input file stream and is used to read information from files. • fstream - This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream
  • 74. Sequential Input and Output Operations • Sequential input and output operations are performed on sequential files • In C++ every sequential file will be associated with two file pointers. • get() - input pointer, it is used to read the content of the file • put()-output pointer, it is used to write content to the file
  • 75. To write content to the file #include<iostream.h> #include<conio.h> #include<fstream.h> void main() { char c,fname[10]; clrscr(); cout<<"Enter file name:"; cin>>fname; ifstream in(fname); if(!in) { cout<<"File Does not Exist"; getch(); return; } cout<<"nn"; while(in.eof()==0) { in.get(c); cout<<c; } getch(); }
  • 76. WRITING THE CONTENT TO THE FILE #include<iostream.h> #include<stdio.h> #include<conio.h> #include<fstream.h> void main() { char c,fname[10]; ofstream out; cout<<"Enter File name:"; cin>>fname; out.open(fname); cout<<"Enter contents to store in file (Enter # at end):n"; while((c=getchar())!='#') { out<<c; } out.close(); getch(); }
  • 77. Random Access Files • Random access file is one that allows accessing records randomly in any order. • To perform random access to a file C++ supports the following functions in addition to get() and put() pointers seekg() - Moves get pointer to specified position seekp() -Moves put pointer to specified position tellg() - Returns the position of get pointer tellp() - Returns the position of get pointer
  • 78.
  • 79. Binary File I/O • binary file stores the content in binary format • read( ) - function reads ‘num’ bytes • write( ) - function writes ‘num’ bytes #include<iostream.h> #include<fstream.h> void main() { ofstream out; out.open(“number”,ios::binary); int k=55; out.write((char *)&k,sizeof(k)); out.close(); }