Managing Console I/O Operations:: Programming in C++ and Data Structures
Managing Console I/O Operations:: Programming in C++ and Data Structures
Stream:
In other words, a program extracts the bytes from an input stream and inserts bytes into
an output stream.
Stream Classes:
Classes that are used to define various streams to deal with both the console and disk files are
called stream classes.
Page 1
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Unformatted IO operations:
The following functions are used to perform unformatted IO operations. They are
We have used the objects cin and cout for the input and output of data of various types. This
has been made possible by overloading operators >> and << to recognize of all the basic C++ types.
Syntax:
cin>>var1>>var2>>…>>var n;
Ex:
int a;
char b;
cin>>a>>b;
Unformatted function cout is used to display the data on the output screen.
Syntax:
cout<<var1<<var2<<…<var n;
Ex:
cout<<a<<b;
Page 2
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
get( ):
get ( ) is a member of istream class for handling single character input operation. There are two
types of get( ) function. we can use both get(char *) and get(void) prototype to fetch a character.
get(char *) version assigns the input character to its arguments and the get(void) versions
returns the input character.
Example program:
#include<iostream.h>
void main( )
{
char c;
cin.get(c); //get a character from the keyboard.
while(c!='\n')
{
cout<<c; //display the character on screen
cin.get(c); //get another character,.
}
}
The above program read a character using get( ) function and display it until press enter. Which
means your character is ‘\n’ (new line).
Note:
We can use the cin.get(c) as follows
c=cin.get( );
It means cin.get(c) is very similar c=cin.get().
Page 3
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
put( ):
It is a member of ostream class, can be used to display a single character. There are two types of
put( ) .we can use both cout.put(‘x’) - it will displays the character x. cout.put(ch) - it will displays
the values of variable ch.
Syntax:
cout.put(charvar) ;
Example:
#include<iostream.h>
void main()
{
char c;
cout<<"enter values";
cin.get(c);
while(c!='\n')
{
cout.put(c);
cin.get(c);
}
}
The below program clearly explains the use of get( ) and put( ) functions.
Example :
#include<iostream.h>
#include<conio.h>
void main()
{
int count=0;
char c;
clrscr();
cout<<"Enter your text :";
cin.get(c);
while(c!='\n')
{
cout.put(c);
count++;
Page 4
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
cin.get(c);
}
cout<<"Number of characters ="<<count<<"\n";
getch();
}
3. getline( ) and write( ):
getline( ):
The getline( ) function reads a whole line of text that ends with a newline character ( Until
press enter). This function can be invoked by using the object cin.
Syntax:
cin.getline(line, size);
Ex:
Example Progrm:
#include<iostream.h>
#include<conio.h>
void main( )
{
char name[50];
clrscr();
cout<<"Enter your name :";
cin.getline(name,50);
cout<<"Your Name is :"<<name;
getch();
}
Output:
Enter your name :vinoth kumar
Your Name is :vinoth kumar
Page 5
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
write( ):
This function is used to display entire line at a time. It can be accessed by using the object
cout.
Syntax:
cout.write(line,size)
Ex:
cout.write(name,40);
Example Program:
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[ ]="Language”;
clrscr();
int n=strlen(name);
Page 6
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
• width( )
• precision( )
• fill( )
• setf( )
• unsetf( )
precision( ): To specify number of digit to be displayed after the decimal point in a real value.
setf( ): To specify format flags that can control the form of output display (such as left-justification and
right –justification)
Example Program:
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
cout.width(5);
cout<<524<<endl;
cout.precision(4);
cout<<sqrt(3)<<endl;
cout.width(15);
cout.fill('&');
cout.setf(ios::scientific,ios::floatfield);
cout<<sqrt(3)<<endl;
cout.setf(ios::hex,ios::basefield);
cout<<48<<endl;
getch();
Page 7
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
}
Output:
524
1.7321
&&&&&1.7321e+00
30
File:
A file is a collection of related data stored in a particular area on the disk. We need to design programs
to perform the read and write operations on the file.
The I/O system of C++ contains a set of classes that define the file handling methods.
These include “ifstream, ofstream and fstream.
These classes are derived from “fstreambase” and from the corresponding iostream
class.
ios
iostream file
iostream
fstream file
fstream base
Page 8
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
ios : ios is a General input/output stream class. It contains basic facilities that are used by all other
input and output classes.
istream: it is input stream. it inherits the properties of ios. Declares input functions such as get( ),
getline( ), and read( ). Contains overloaded extraction operator >>
ostream : it is output stream. it inherits properties of ios. Declares output functions put( ) and write().
Contains overloaded insertion operator <<.
iostream : it is input /output stream. It inherits the properties of ios, istream and ostream through
multiple inheritances and thus contains all the input and output functions.
filebuf : Its purpose is to set the file buffers to read and write.
fstreambase: Its Provides operations common to the file streams. Servers as a base for fstream,
ifstream and ofstream class. Contains open( ) and close( ) functions.
ifstream: This class provides input operations. Contains open () method with default input mode. It
inherits get(), geline(), read(), seekg() and tellg() functions from istream.
ofstream: This class provides output operations. Contains open () method with default output mode.
It inherits put(), seekp(), tellp() and write() function from ostream.
fstream: It inherits all the member function from istream and ostream classes through iostream.
Opening a File:
Using constructor:
Syntax:
file_stream-class stream-objectname(“filename”);
Page 9
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Ex:
ofstream k(“result.txt”);
In the above example k is an object in the type of ofstream and it opens a file result.txt.
Using member function open ( ):
Syntax:
file_stream-class stream-objectname;
stream-objectname . open(“filename”);
Example:
ofstream k;
k . open(“result.txt”);
In the above example code k is an object in the type of ofstream. So using object k we can
access the member of ofstream function open ().
File Opening modes:
File opening mode specifies the purpose for which file is opened. If we open a file using
ofstream object, by default it is in writing mode. Similarly if we open a file using ifstream it is in
reading mode.
Syntax:
Stream-Objectname . open(“filename”,mode);
Ex:
k. open(“abc.txt”, ios :: app);
Parameter Meaning
ios::app Append to end of file
ios::ate Go to end-of-file on opening
ios::binary Binary file
ios::in Open file for reading only
ios::out Open file for writing only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exist
ios::trunk Delete the contents of the file if it exists
Example program for opening and closing of a file:
Page 10
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
ofstream x("mypro23.txt");
cout<<x.fail();
if(x.fail())
{
cout<<"This file cannot be open\n";
exit (0);
}
x.close();
}
Functions for read and write operation in a file:
put( ):
This function is used to write a single character into a file.
Syntax:
Object . put(char_val)
Ex:
o.put(“c”);
In the above example character “c” is written into a file using put() function.
Example:
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char name[50];
int n,i;
Page 11
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Example:
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char ch;
ifstream a("namefil.txt");
Page 12
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
if(a.fail())
{
cout<<"this file cannot be open";
exit(9);
}
while(!a.eof())
{
a.get(ch);
cout<<ch<<endl;
}
a.close();
}
Write String into a file:
Object_name<< function is used to write a string into a file.
Syntax:
Objectname<<string;
Ex:
k<<”sathish kumar”;
Example:
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
ofstream n("myfriends.txt");
if(n.fail())
{
cout<<"The file cannot be open";
exit(1);
Page 13
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
}
n<<"Raja\n";
n<<"sathish\n";
n<<"Ramesh\n";
n.close();
}
getline():
This function is used to read a string from a file.
Syntax:
Obj_name.getline(str_var,size);
Ex:
n.getline(name,25);
Example:
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
char names[50];
ifstream n("myfriends.txt");
if(n.fail())
{
cout<<"The file cannot be open";
exit(1);
}
while(!n.eof())
{
n.getline(names,40);
cout<<names<<endl;
}
n.close();
Page 14
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
}
write():
This function is used to write an object into a file.
Syntax:
File_obj.write((char *)&cl_obj,sizeof(cl_obj));
Ex:
k.write((char *)&y,sizeof(y));
Example:
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
class secondcs
{
int rno;
char name[15];
public:
void read(void)
{
cout<<"Enter student sno and name :\n";
cin>>rno>>name;
}
};
void main()
{
secondcs x,y;
x.read();
y.read();
ofstream n("myfriends.dat");
if(n.fail())
{
cout<<"The file cannot be open";
Page 15
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
exit(1);
}
n.write((char *)&x,sizeof(x));
n.write((char *)&y,sizeof(y));
n.close(); }
read():
This function is used to read an object from a file.
Syntax:
File_obj((char *)&cl_obj, sizeof(cl_obj));
Ex:
n.read((char *)&x, sizeof(x));
Example:
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
class secondcs
{
char name[15];
int rno;
public:
void print(void)
{
cout<<"sno : "<<rno<<endl;
cout<<"name : "<<name<<endl;
}
};
void main()
{
secondcs x;
ifstream n("compsci.txt");
if(n.fail())
Page 16
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
{
cout<<"The file cannot be open";
exit(1);
}
while(!n.eof())
{
n.read((char *)&x,sizeof(x));
x.print();
}
n.close();
}
File pointers and their manipulators:
Each file has two file pointers – input pointer and output pointer. These file pointers are used to
move the file pointer to the particular byte, while reading and writing in a file.
Functions for manipulation of file pointers:
seekg(): Moves get pointer (input) to a specified location.
seekp(): Moves put pointer (output) to a specified location.
tellg(): Gives the current position of the get pointer.
tellp(): Gives the current position of the put pointer.
Page 17
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Page 18
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
#include<conio.h>
void main(int argc,char *argv[])
{
clrscr();
cout<<"Your friends are :\n";
for(int i=1;i<=argc;i++)
cout<<argv[i]<<endl;
}
Input/Output:
C:\tcc>mypro sathish vinoth kannan
Your friends are :
sathish
vinoth
kannan
Data Structures:
The way information is organized in the memory of a computer is called a “data structure”A
data structure is a way of organizing data that consider not only the item stored, but also their
relationship to each other. Data structure is also called as “fundamental data structure or classic data
structure”.
Primitive data structures are predefined types of data, which are supported by the programming
language.
Page 19
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Non primitive data structures are not defined by the programming languages, but are derived
from primitive data structures.
Data Structure is classified into two types. They are linear and non-linear data structure. Linear data
structure includes Array, Stack, Queue and linked list. Non-linear data structure includes Tree, Graph,
Table and Sets. The below diagram clearly show this classification.
1 front rear
Page 20
……..
……..
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
2 top
………………………
Linked list
Tree Graph
Traversing: Accessing each element in the list is called traversing. This accessing and processing is
sometimes called visiting the record.
Searching: Finding the location of the item in the list is called searching.
Sorting: Arranging the records in some logical manner is called sorting.( Sorting records
alphabetically, etc).
Merging: Combining the records from two sorted lists into single sorted list is called merging.
Page 21
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Array:
An array is a finite set of homogeneous data element stored in a common name. We can store
and retrieve elements in an array using index (or subscript). Array data structure allocates continuous
memory spaces in memory.
If only one subscript or index is required to refer all the elements in an array then the array can
be called as “one-dimensional” array.
Let LA be a linear array in memory of the computer. Recall the memory of the computer is
simply a sequence of addressed location as pictured in below figure. Array data structure allocates
continuous memory spaces in memory. For example in C if we declare an array in the type of integer
with the size of 50, then it needs 100 bytes continuous space in memory.
DATA
1000
1001
1002
1003
1004
Operations on Array:
Traversing:
Here LA is a linear array with lower bound LB and upper bound UB. This algorithm traverses
LA applying an operation PROCESS to each element of LA.
Page 22
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Insertion:
Let A be a collection of data elements in the memory of the computer. The term “Insertion”
refers to the operation of adding another element to the collection.
Here LA is a linear array with N elements and K is a positive integer such that K<=N. This
algorithm inserts an element ITEM into the Kth position in LA.
Deletion:
Deletion refers to the operation of removing one of the elements from the list A.
In the below algorithm LA is a linear array with N element and K is a positive integer such that
K<=N. This algorithm deletes the K th element from the linear array LA.
1. Set ITEM:=LA[K]
Page 23
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Searching:
Searching refers to the operation of finding the location LOC of ITEM in the list.
Here DATA is a linear array with N elements, and ITEM is a given element to find the position.
This algorithm finds the LOC or ITEM in DATA, or sets LOC:=0 if the search is unsuccessful.
Multi-Dimensional Array:
1. Two-Dimensional Arrays
A two dimensional m x n array ARR is a collection of m.n data elements such that each element is
specified by a pair of integers (such as J and K), called subscript, with the property that
Page 24
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
In other words a two-dimensional array is an array in which elements are referenced by tow
subscript. It is generally used to represent the matrix. In the below matrix M represents the number of
rows in the matrix and N represents number of columns in the matrix.
a) Row-major order
b) Column-major order
In the row-major order, elements of a matrix are stored on a row-by-row basis that is all the
elements in first row, then the second row and so on. On the other hand, in column-major order,
elements are stored column-by-column that is, all the elements in first column and then second
column and so on.
a11 1 a11
a12 2 a21
a13 3 a31
a14 4 a12
a21 5 a22
a22 6 a32
Page 25
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
a23 7 a13
a24 8 a23
a31 9 a33
a32 10 a14
a33 11 a24
a34 12 a34
Row-Major Order Column-Major Order
A three dimensional array can be compared with a book whereas two-dimensional and one
dimensional arrays can be compared with a page and a line respectively. Here, three major
dimensional can be termed as row, column and page.
N-Dimensional Array:
From the representation of 2-D and 3-D, we can extend our idea to store an n-dimensional array.
Here, to identify an element, we need n indices or subscript i1, i2…in.
Pointer Array:
Address of memory location is pointer and an array containing pointer as its element is known
as pointer array.
Page 26
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]
Page 27