7/29/2019 oops-unit V
1/35
Streams and IO
Streams are pipe like constructors used for
providing IO.
When a programmer needs to handle inputfrom or output to external entities,then
streams are used by c++.
The stream is the central concept of theiostream classes
7/29/2019 oops-unit V
2/35
Output streams
An output stream object is a destination for bytes.
The three most important output stream classare
, and ostrstream.ofstream,ostream
The ostream class, through the derived class, supports the predefined streambasic_ostream
objects:cout standard output
cerr standard error with limited bufferingclog similar to cerrbut with full buffering
http://msdn.microsoft.com/en-us/library/e9cabcax(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/0w301t0t(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/760t8w1z(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/760t8w1z(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/0w301t0t(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/e9cabcax(v=VS.71).aspx7/29/2019 oops-unit V
3/35
Input streams
An input stream object is a source of bytes.
The three most important input stream
istrstream, andifstream,istreamclasses are
The istream class is best used for sequential
text-mode input. You can configure objects
of class istream for buffered or unbuffered
operation. All functionality of the base
class,ios, is included in istream. You will
rarelconstruct objects from class istream.
Instead, you will generally use the
http://msdn.microsoft.com/en-us/library/06w5ktxs(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/ae1k9a9f(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/a93teef1(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/a93teef1(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/ae1k9a9f(v=VS.71).aspxhttp://msdn.microsoft.com/en-us/library/06w5ktxs(v=VS.71).aspx7/29/2019 oops-unit V
4/35
Formatting I/O
Formatting using Ios functions
Width()-It specifies the width for display.the output will take up thewidth specified.used in alignng vertical column of numeric items.
Precision()-It specifies the precision of the floating point
number.Default precision is six digits after decimal point Fill()-it specifies the character for filling up the unused prion of the
field.It is usually usd with the width member function.
Setf()-The function specifies the format flags that controls outputdisplay like left or right justification,padding after signsymbol,scientific notation display,displaying abse of the number
Unsetf()-This function provides undo operation for above mentionedoperations with setf.
7/29/2019 oops-unit V
5/35
.The prototype of the function is
functionname
The functions set new value to the stream andretutn value.The width function sets new width to
the argument specified and returns old width.,Theprecision function sets new precision and returnsold precision.
Member functions of Ios
7/29/2019 oops-unit V
6/35
I/O manipulators
Manipulators are special functions for
formatting
The choice between manipulators and ios
functions to solve formatting problemssometimes depends upon the user.
Equivalent manipulators for some of the io
functions are:Setw(),setprecision(),setfill(),setiosflags(),rese
tiosflags().
7/29/2019 oops-unit V
7/35
Unlike Ios,manipulators do not return theprevious status
Manipulators can write our own manipulatorand use it in the programmarksheet printing
program can use it for printing
Ios functions are singleThey cannot becombined to have multiple effects
together.When a large set of formattingoptions are used,manipulators are used to
write and produce more readable code.Ios functions need whereas
manipulators need .
Difference between ios and manipulators
7/29/2019 oops-unit V
8/35
#include #include
/*
* Input using cin
*/
int main () {
char myline[256];=
Example program
7/29/2019 oops-unit V
9/35
Object Serialization
7/29/2019 oops-unit V
10/35
Object Serialization
Simple persistence method which provides
a program the ability to read or write a whole
object to and from a stream of bytes
Allows Java objects to be encoded into a
byte stream suitable for streaming to a file
on disk or over a network
The class must implement the Serializable
interface (java.io.Serializable), which does
not declare any methods, and have
accessors and mutators for its attributes
7/29/2019 oops-unit V
11/35
Object Serialization :example pgm
// create output stream
File file = new
File("teams_serialize.ser");String fullPath =
file.getAbsolutePath();
fos = newFileOutputStream(fullPath);
// open output stream and store
7/29/2019 oops-unit V
12/35
Object persistence
One of the most critical tasks that
applications have to perform is to save and
restore data
Persistence is the storage of data from
working memory so that it can be restored
when the application is run again
In object-oriented systems, there are several
ways in which objects can be made
persistent
The choice of ersistence method is an
7/29/2019 oops-unit V
13/35
C++ Namespaces
A mechanism for logically grouping
declarations and definitions into a common
declarative region
7/29/2019 oops-unit V
14/35
C++ Namespaces
The contents of the namespace can be
accessed by code inside or outside the
namespace
Use the scope resolution operator to access
elements from outside the namespace
Alternatively, the usingdeclaration allows the
names of the elements to be used directly
7/29/2019 oops-unit V
15/35
C++ Namespaces
Creating a namespacenamespace smallNamespace
{
int count = 0;void abc();
} //end smallNamespace
Using a namespace
usingnamespace smallNamespace;
count +=1;
abc();
7/29/2019 oops-unit V
16/35
STD Namespaces
Items declared in the C++ Standard Library
are declared in the stdnamespace
C++ include files for several functions are inthe stdnamespace
To include input and output functions from the
C++ library, writeinclude
usingnamespace std;
7/29/2019 oops-unit V
17/35
Ansi 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
7/29/2019 oops-unit V
18/35
Ansi string class syntax pgm
#include
using namespace std;
...
string first_name = "Bjarne";string last_name;
last_name = "Stroustrup";
string names = first_name + " " + last_name;
cout
7/29/2019 oops-unit V
19/35
Ansi string class member functions
Member functions
The string class defines many member functions. A few of the basicones are described below:
A string object may defined without an initializing value, in which caseits 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";
7/29/2019 oops-unit V
20/35
Standard Template Library
The standard template library (STL) containsContainers
Algorithms
Iterators
A containeris a way that stored data is
organized in memory, for example an array of
elements.
Algorithms in the STL are procedures that are
applied to containers to process their data, for
example search for an element in an array, or
sort an array.
C t i It t Al ith
7/29/2019 oops-unit V
21/35
Containers, Iterators, Algorithm
Container
AlgorithmIterator
Container
Iterator
Algorithm
Objects
Iterator
Iterator
Algorithm
Algorithms use iterators to interact with objectsstored in containers
7/29/2019 oops-unit V
22/35
Containers
A container is a way to store data, eitherbuilt-in data
types like int and float, or class objects
The STL provides several basic kinds ofcontainers
: one-dimensional array
: double linked list : double-ended queue
: queue
: stack
: set
7/29/2019 oops-unit V
23/35
Sequence Containers
A sequence container stores a set ofelements in
sequence, in other words each element
(exceptfor the first and last one) is preceded byone
specific element and followed byanother, ,
and are sequentialcontainers
In an ordinary C++ array the size is
7/29/2019 oops-unit V
24/35
Sequence Containers
is a double linked list (each elementhas
points to its successor and predecessor), it
isquick to insert or delete elements but has
slow
random access is a double-ended queue, that
means one
can insert and delete elements from both
7/29/2019 oops-unit V
25/35
Associative Containers
An associative container is non-sequential
but uses
a keyto access elements. The keys,typically a number or a string, are used by
the container to arrange the stored elements
in a specific order,
for example in a dictionary the entries are
ordered
alphabetically.
7/29/2019 oops-unit V
26/35
Associative Containers
A stores a number of items whichcontain keys
The keys are the attributes used to order the
items,for example a set might store objects of the
class
Person which are ordered alphabetically usingtheir name
A stores pairs of objects: a key object
and
7/29/2019 oops-unit V
27/35
vector
array_
Iterators
Iterators are pointer-like entities that areused to
access individual elements in a container.
Often they are used to move sequentiallyfrom element to element, a process called
iteratingthrough a container.17
4
23
12
size_ 4
vector::iterator
The iterator corresponding tothe class vector is ofthe type vector::iterator
7/29/2019 oops-unit V
28/35
Iterators
One can have multiple iterators pointing todifferent or identical elements in the
containervector v
array_ 17
4
23
12
size_ 4i3
i1
i2
7/29/2019 oops-unit V
29/35
Iterators#include
#include
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector v(arr, arr+4); // initialize vectorwith C array
for (vector::iterator i=v.begin();
i!=v.end(); i++)// initialize i with pointer to first element of v
// i++ increment iterator, move iterator to next
element
7/29/2019 oops-unit V
30/35
File handling in C++
Introduction to File Handling
Data entered once, required later again
Same Data to be used by others
Data required again by the same program
Files and Streams
7/29/2019 oops-unit V
31/35
I/O Streams
StreamDescription
cin
Standard input streamcout
Standard output stream
cerr
Standard error stream
7/29/2019 oops-unit V
32/35
ofstream
Output file stream Class
open() is a member function of the class
ofstreamInherited functions of ofstream class, from
the class ostream are
put()
write()
seekp()
tellp()
7/29/2019 oops-unit V
33/35
fstream
It supports files for simultaneous input and output
fstream is derived fromifstream
ofstream
iostream
They are parent classes and fstream is the child classMember functions of the class fstream
open
close
close all
seekg
seekp
tellg
tellp
7/29/2019 oops-unit V
34/35
//This program creates a file called message.dat
#include //Required for file
I/Oint main()
{
ofstream myfile (message.dat);
If (!myfile)
{
//check if the file is
opened or notcout
7/29/2019 oops-unit V
35/35
Function in C++Function Prototype
Function Call
Function Definition