1. Streams and IOStreams and IO
Streams are pipe like constructors used forStreams are pipe like constructors used for
providing IO.providing IO.
When a programmer needs to handle inputWhen a programmer needs to handle input
from or output to external entities,thenfrom or output to external entities,then
streams are used by c++.streams are used by c++.
The stream is the central concept of theThe stream is the central concept of the
iostream classesiostream classes
2. Output streamsOutput streams
An output stream object is a destination for bytes.An output stream object is a destination for bytes.
The three most important output stream classareThe three most important output stream classare
ostream, ofstream, and ostrstreamostream, ofstream, and ostrstream..
TheThe ostreamostream class, through the derived classclass, through the derived class
basic_ostream, supports the predefined streambasic_ostream, supports the predefined stream
objects:objects:coutcout standard outputstandard output
cerrcerr standard error with limited bufferingstandard error with limited buffering
clogclog similar tosimilar to cerrcerr but with full bufferingbut with full buffering
3. Input streamsInput streams
An input stream object is a source of bytes.An input stream object is a source of bytes.
The three most important input streamThe three most important input stream
classes are istream, ifstream, and istrstreamclasses are istream, ifstream, and istrstream
The istream class is best used forThe istream class is best used for
sequential text-mode input. You cansequential text-mode input. You can
configure objects of class istream forconfigure objects of class istream for
buffered or unbuffered operation. Allbuffered or unbuffered operation. All
functionality of the base class,ios, isfunctionality of the base class,ios, is
included in istream. You will rarelconstructincluded in istream. You will rarelconstruct
objects from class istream. Instead, you willobjects from class istream. Instead, you will
4. Formatting I/OFormatting I/O
Formatting using Ios functionsFormatting using Ios functions
Width()-It specifies the width for display.the output will take up theWidth()-It specifies the width for display.the output will take up the
width specified.used in alignng vertical column of numeric items.width specified.used in alignng vertical column of numeric items.
Precision()-It specifies the precision of the floating pointPrecision()-It specifies the precision of the floating point
number.Default precision is six digits after decimal pointnumber.Default precision is six digits after decimal point
Fill()-it specifies the character for filling up the unused prion of theFill()-it specifies the character for filling up the unused prion of the
field.It is usually usd with the width member function.field.It is usually usd with the width member function.
Setf()-The function specifies the format flags that controls outputSetf()-The function specifies the format flags that controls output
display like left or right justification,padding after signdisplay like left or right justification,padding after sign
symbol,scientific notation display,displaying abse of the numbersymbol,scientific notation display,displaying abse of the number
Unsetf()-This function provides undo operation for above mentionedUnsetf()-This function provides undo operation for above mentioned
operations with setf.operations with setf.
5. ..The prototype of the function isThe prototype of the function is
>>old value of stream>functionold value of stream>function
name<specified new valuename<specified new value<<
The functions set new value to the stream andThe functions set new value to the stream and
retutn value.The width function sets new width toretutn value.The width function sets new width to
the argument specified and returns old width.,Thethe argument specified and returns old width.,The
precision function sets new precision and returnsprecision function sets new precision and returns
old precisionold precision..
Member functions of Ios
6. I/O manipulatorsI/O manipulators
Manipulators are special functions forManipulators are special functions for
formattingformatting
The choice between manipulators and iosThe choice between manipulators and ios
functions to solve formatting problemsfunctions to solve formatting problems
sometimes depends upon the usersometimes depends upon the user..
Equivalent manipulators for some of the ioEquivalent manipulators for some of the io
functions arefunctions are::
Setw(),setprecision(),setfill(),setiosflags(),reseSetw(),setprecision(),setfill(),setiosflags(),rese
tiosflagstiosflags().().
7. Unlike Ios,manipulators do not return theUnlike Ios,manipulators do not return the
previous statusprevious status
Manipulators can write our own manipulatorManipulators can write our own manipulator
and use it in the programmarksheet printingand use it in the programmarksheet printing
program can use it for printingprogram can use it for printing
Ios functions are singleThey cannot beIos functions are singleThey cannot be
combined to have multiple effectscombined to have multiple effects
together.When a large set of formattingtogether.When a large set of formatting
options are used,manipulators are used tooptions are used,manipulators are used to
write and produce more readable codewrite and produce more readable code..
Ios functions need <iotsream>whereasIos functions need <iotsream>whereas
manipulators need <iomanipmanipulators need <iomanip>.>.
Difference between ios and manipulators
10. Object SerializationObject Serialization
Simple persistence method which providesSimple persistence method which provides
a program the ability to read or write aa program the ability to read or write a
whole object to and from a stream of byteswhole object to and from a stream of bytes
Allows Java objects to be encoded into aAllows Java objects to be encoded into a
byte stream suitable for streaming to a filebyte stream suitable for streaming to a file
on disk or over a networkon disk or over a network
The class must implement theThe class must implement the SerializableSerializable
interface (interface (java.io.Serializablejava.io.Serializable), which does), which does
not declare any methods, and havenot declare any methods, and have
accessors and mutators for its attributesaccessors and mutators for its attributes
11. Object Serialization :example pgmObject Serialization :example pgm
////create output streamcreate output stream
File file = newFile file = new
File("teams_serialize.serFile("teams_serialize.ser");");
String fullPath =String fullPath =
file.getAbsolutePathfile.getAbsolutePath();();
fos = newfos = new
FileOutputStream(fullPathFileOutputStream(fullPath););
////open output stream and storeopen output stream and store
12. Object persistenceObject persistence
One of the most critical tasks thatOne of the most critical tasks that
applications have to perform is to save andapplications have to perform is to save and
restore datarestore data
PersistencePersistence is the storage of data fromis the storage of data from
working memory so that it can be restoredworking memory so that it can be restored
when the application is run againwhen the application is run again
In object-oriented systems, there areIn object-oriented systems, there are
several ways in which objects can be madeseveral ways in which objects can be made
persistentpersistent
The choice of persistence method is anThe choice of persistence method is an
13. C++ NamespacesC++ Namespaces
A mechanism for logically groupingA mechanism for logically grouping
declarations and definitions into a commondeclarations and definitions into a common
declarative regiondeclarative region
14. C++ NamespacesC++ Namespaces
The contents of the namespace can beThe contents of the namespace can be
accessed by code inside or outside theaccessed by code inside or outside the
namespacenamespace
–Use the scope resolution operator to accessUse the scope resolution operator to access
elements from outside the namespaceelements from outside the namespace
–Alternatively, theAlternatively, the usingusing declaration allows thedeclaration allows the
names of the elements to be used directlynames of the elements to be used directly
15. C++ NamespacesC++ Namespaces
Creating a namespaceCreating a namespace
namespace smallNamespacenamespace smallNamespace
}}
intint count = 0count = 0;;
voidvoid abcabc();();
} //} //end smallNamespaceend smallNamespace
Using a namespaceUsing a namespace
usingusing namespacenamespace smallNamespacesmallNamespace;;
count +=1count +=1;;
abcabc();();
16. STD NamespacesSTD Namespaces
Items declared in the C++ Standard LibraryItems declared in the C++ Standard Library
are declared in theare declared in the stdstd namespacenamespace
C++C++ includeinclude files for several functions are infiles for several functions are in
thethe stdstd namespacenamespace
–To include input and output functions from theTo include input and output functions from the
C++ library, writeC++ library, write
include <iostreaminclude <iostream<<
usingusing namespacenamespace stdstd;;
17. Ansi string objectsAnsi string objects
The ANSI string class implements a first-
class character string data type that avoids
many problems
associated with simple character arrays
("C-style strings"). You can define a string
object very
simply, as shown in the following example
19. Ansi string class member functionsAnsi string class member functions
Member functions
The string class defines many member functions. A few of the basic
ones are described below:
A string object may defined without an initializing value, in which case
its initial
value is an empty string (zero length, no characters(:
string str1;
A string object may also be initialized with
a string expression:
string str2 = str1;
string str3 = str1 + str2;
string str4 (str2(; // Alternate form
a character string literal:
string str4 = "Hello there";
20. Standard Template LibraryStandard Template Library
The standard template library (STL( containsThe standard template library (STL( contains
–ContainersContainers
–AlgorithmsAlgorithms
–IteratorsIterators
AA containercontainer is a way that stored data isis a way that stored data is
organized in memory, for example an array oforganized in memory, for example an array of
elementselements..
AlgorithmsAlgorithms in the STL are procedures that arein the STL are procedures that are
applied to containers to process their data, forapplied to containers to process their data, for
example search for an element in an array, orexample search for an element in an array, or
sort an arraysort an array..
21. Containers, Iterators, AlgorithmsContainers, Iterators, Algorithms
Container
Algorithm
Iterator
Container
Iterator
Algorithm
Objects
Iterator
Iterator
Algorithm
Algorithms use iterators to interact with objects
stored in containers
22. ContainersContainers
A container is a way to store data, eitherA container is a way to store data, either
built-in databuilt-in data
types like int and float, or class objectstypes like int and float, or class objects
The STL provides several basic kinds ofThe STL provides several basic kinds of
containerscontainers
–>>vector> : one-dimensional arrayvector> : one-dimensional array
–>>list> : double linked listlist> : double linked list
–>>deque> : double-ended queuedeque> : double-ended queue
–>>queue> : queuequeue> : queue
–>>stack> : stackstack> : stack
23. Sequence ContainersSequence Containers
A sequence container stores a set ofA sequence container stores a set of
elements inelements in
sequence, in other words each elementsequence, in other words each element
(except(except
for the first and last one( is precededfor the first and last one( is preceded
by oneby one
specific element and followed byspecific element and followed by
another, >vectoranother, >vector>,>,
>>list> and >deque> are sequentiallist> and >deque> are sequential
containerscontainers
In an ordinary C++ array the size isIn an ordinary C++ array the size is
24. Sequence ContainersSequence Containers
>>list> is a double linked list (each elementlist> is a double linked list (each element
hashas
points to its successor and predecessor(, itpoints to its successor and predecessor(, it
isis
quick to insert or delete elements but hasquick to insert or delete elements but has
slowslow
random accessrandom access
>>deque> is a double-ended queue, thatdeque> is a double-ended queue, that
means onemeans one
can insert and delete elements from bothcan insert and delete elements from both
25. Associative ContainersAssociative Containers
An associative container is non-sequentialAn associative container is non-sequential
but usesbut uses
aa keykey to access elements. The keys,to access elements. The keys,
typically a number or a string, are used bytypically a number or a string, are used by
the container to arrange the storedthe container to arrange the stored
elements in a specific orderelements in a specific order,,
for example in a dictionary the entries arefor example in a dictionary the entries are
orderedordered
alphabeticallyalphabetically..
26. Associative ContainersAssociative Containers
A >set> stores a number of items whichA >set> stores a number of items which
contain keyscontain keys
The keys are the attributes used to order theThe keys are the attributes used to order the
itemsitems,,
for example a set might store objects of thefor example a set might store objects of the
classclass
Person which are ordered alphabetically usingPerson which are ordered alphabetically using
their nametheir name
A >map> stores pairs of objects: a key objectA >map> stores pairs of objects: a key object
andand
27. vector<int>
array_
IteratorsIterators
Iterators are pointer-like entities that areIterators are pointer-like entities that are
used toused to
access individual elements in a containeraccess individual elements in a container..
Often they are used to move sequentiallyOften they are used to move sequentially
from element to element, a process calledfrom element to element, a process called
iteratingiterating through a containerthrough a container..
17
4
23
12
size_ 4
vector<int>::iterator
The iterator corresponding to
the class vector<int> is of
the type vector<int>::iterator
28. IteratorsIterators
One can have multiple iterators pointing toOne can have multiple iterators pointing to
different or identical elements in thedifferent or identical elements in the
containercontainervector<int> v
array_ 17
4
23
12
size_ 4
i3
i1
i2
29. IteratorsIterators
##include <vectoinclude <vectorr<<
##include <iostreaminclude <iostream<<
int arr[] = { 12, 3, 17, 8 }; // standard C arrayint arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int< v(arr, arr+4); // initialize vectorvector<int< v(arr, arr+4); // initialize vector
with C arraywith C array
for (vector<int<::iterator i=v.begin(); i!for (vector<int<::iterator i=v.begin(); i!
=v.end(); i=v.end(); i++)++)
////initialize i with pointer to first element of vinitialize i with pointer to first element of v
////i++ increment iterator, move iterator to nexti++ increment iterator, move iterator to next
elementelement
30. File handling in CFile handling in C++++
Introduction to File HandlingIntroduction to File Handling
–Data entered once, required later againData entered once, required later again
–Same Data to be used by othersSame Data to be used by others
–Data required again by the same programData required again by the same program
Files and StreamsFiles and Streams
32. ofstreamofstream
Output file stream ClassOutput file stream Class
open() is a member function of the classopen() is a member function of the class
ofstreamofstream
Inherited functions of ofstream class, fromInherited functions of ofstream class, from
the class ostream arethe class ostream are
–putput()()
–writewrite()()
–seekpseekp()()
–tellptellp()()
33. fstreamfstream
It supports files for simultaneous input and outputIt supports files for simultaneous input and output
fstream is derived fromfstream is derived from
–ifstreamifstream
–ofstreamofstream
–iostreamiostream
They are parent classes and fstream is the child classThey are parent classes and fstream is the child class
Member functions of the class fstreamMember functions of the class fstream
–openopen
–closeclose
–close allclose all
–seekgseekg
–seekpseekp
–tellgtellg
–tellptellp
34. ////This program creates a file called “message.datThis program creates a file called “message.dat””
##include <fstream.h<include <fstream.h<//Required for file I/O//Required for file I/O
int mainint main()()
}}
ofstream myfile (“message.datofstream myfile (“message.dat”);”);
If (!myfileIf (!myfile))
}}
////check if the file is opened orcheck if the file is opened or
notnot
cout<<"n Cannot open this filecout<<"n Cannot open this file";";
return 1return 1;;
{{
myfile <<“When an apple fell, Newton was disturbedmyfile <<“When an apple fell, Newton was disturbed
n”;
35. Function in CFunction in C++++
Function PrototypeFunction Prototype
Function CallFunction Call
Function DefinitionFunction Definition