SlideShare una empresa de Scribd logo
1 de 35
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
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
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
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.
..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
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().().
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
##include <iostream.h>include <iostream.h>
#include <fstream.h>#include <fstream.h>
/*/*
* Input using cin* Input using cin
*/*/
int main () {int main () {
char myline[256];char myline[256];
Example program
Object SerializationObject Serialization
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
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
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
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
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
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();();
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;;
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
Ansi string class syntax pgmAnsi string class syntax pgm
#include <string<
using namespace std;
...
string first_name = "Bjarne";
string last_name;
last_name = "Stroustrup";
string names = first_name + " " + last_name;
cout << names << endl;
names = last_name + ", " + first
" +first_name;
cout << names << endl;
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";
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..
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
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
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
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
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..
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
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
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
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
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
I/O StreamsI/O Streams
StreamDescription
cin
Standard input stream
coutStandard output
stream
cerrStandard error
stream
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()()
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
////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”;
Function in CFunction in C++++
Function PrototypeFunction Prototype
Function CallFunction Call
Function DefinitionFunction Definition

Más contenido relacionado

La actualidad más candente

C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
Kumaran K
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slides
Dr-archana-dhawan-bajaj
 

La actualidad más candente (20)

Python programming
Python  programmingPython  programming
Python programming
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Basics of building a blackfin application
Basics of building a blackfin applicationBasics of building a blackfin application
Basics of building a blackfin application
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
The Ring programming language version 1.8 book - Part 116 of 202
The Ring programming language version 1.8 book - Part 116 of 202The Ring programming language version 1.8 book - Part 116 of 202
The Ring programming language version 1.8 book - Part 116 of 202
 
C++11
C++11C++11
C++11
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular ExpressionPerl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
 
Python
PythonPython
Python
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Modern C++
Modern C++Modern C++
Modern C++
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slides
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 

Destacado (11)

Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Java IO
Java IOJava IO
Java IO
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
Data mining
Data miningData mining
Data mining
 

Similar a Unit v

Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
Princess Sam
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
Bharat17485
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
SukhpreetSingh519414
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
DeepasCSE
 

Similar a Unit v (20)

programming language in c&c++
programming language in c&c++programming language in c&c++
programming language in c&c++
 
098ca session7 c++
098ca session7 c++098ca session7 c++
098ca session7 c++
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
 
C
CC
C
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Console i/o for c++
Console i/o for c++Console i/o for c++
Console i/o for c++
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
 
THE IO LIBRARY in C++
THE IO LIBRARY in C++THE IO LIBRARY in C++
THE IO LIBRARY in C++
 

Último

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Último (20)

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 

Unit v

  • 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
  • 8. ##include <iostream.h>include <iostream.h> #include <fstream.h>#include <fstream.h> /*/* * Input using cin* Input using cin */*/ int main () {int main () { char myline[256];char myline[256]; Example program
  • 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
  • 18. Ansi string class syntax pgmAnsi string class syntax pgm #include <string< using namespace std; ... string first_name = "Bjarne"; string last_name; last_name = "Stroustrup"; string names = first_name + " " + last_name; cout << names << endl; names = last_name + ", " + first " +first_name; cout << names << endl;
  • 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
  • 31. I/O StreamsI/O Streams StreamDescription cin Standard input stream coutStandard output stream cerrStandard error stream
  • 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