0% found this document useful (0 votes)
92 views27 pages

Managing Console I/O Operations:: Programming in C++ and Data Structures

The document discusses C++ input/output (I/O) operations and file handling. It describes streams as sequences of bytes that act as sources or destinations of data. Stream classes like istream and ostream are used for formatted and unformatted console I/O, while file stream classes like ifstream and ofstream handle file I/O. The functions get(), put(), getline(), and write() are used for unformatted I/O, while width(), precision(), fill(), setf(), and unsetf() control formatted output formatting and flags. Files are collections of related data stored on disk, and file stream classes provide methods to perform read and write operations on files.

Uploaded by

char les
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views27 pages

Managing Console I/O Operations:: Programming in C++ and Data Structures

The document discusses C++ input/output (I/O) operations and file handling. It describes streams as sequences of bytes that act as sources or destinations of data. Stream classes like istream and ostream are used for formatted and unformatted console I/O, while file stream classes like ifstream and ofstream handle file I/O. The functions get(), put(), getline(), and write() are used for unformatted I/O, while width(), precision(), fill(), setf(), and unsetf() control formatted output formatting and flags. Files are collections of related data stored on disk, and file stream classes provide methods to perform read and write operations on files.

Uploaded by

char les
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Managing Console I/O Operations:


C++ uses the concept of stream and stream classes to implement its I/O operations with the
console and disk files.

Stream:

A stream is a sequence of bytes. It act as either as a source or as a destination. The source


stream that provides data to the program is called the input stream. The destination stream that
receives data from the program is called output 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.

Fig:Stream classes for console I/O operations.

Page 1
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

ios: General Input Output Stream class.


istream: for formatted and unformatted Input operations.
ostream: for formatted and unformatted output operations.
iostream: provides the facility for handling both input and output operations.
streambuf: Provides an interface to physical devices through buffers.

Unformatted IO operations:

The following functions are used to perform unformatted IO operations. They are

1. cin>> and cout<<

2. put() and get( )

3. getline( ) and write( )

1. cin>> and cout<<:

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.

Unformatted function cin used to read the data.

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]

2. get( ) and put( ):

 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.

get(char *) versions is used as follows:


Syntax:
cin.get(char_var)
Ex:
char c;
cin.get(c);

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

The get(void) versions is used 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:

char name[40]; cin.getline(name, 40);

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);

for( int i=0;i<=n;i++)


{
cout.write(name,i);
cout<<endl;
}
getch();
}
Output:
L
La
Lan
Lang
Langu
Langua
Languag
Language

Page 6
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Formatted console IO:


The following functions are used to perform formatted IO operations. They are

• width( )

• precision( )

• fill( )

• setf( )

• unsetf( )

width( ): To specify the size for output value on the screen.

precision( ): To specify number of digit to be displayed after the decimal point in a real value.

fill( ): To specify the character to be displayed in the unused portion of a field.

setf( ): To specify format flags that can control the form of output display (such as left-justification and
right –justification)

unsetf( ): To clear the flag.

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

1. Working with files:

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.

1.1 classes for File Stream Operations:

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

istream streambuf ostream

iostream

ifstream fstream ofstream filebuf

fstream file

fstream base
Page 8
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

fig: stream classes for file operations

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.

streambuf: It provides an interface to physical devices through buffers.

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:

A file can be opened in two ways. They are

1. Using the constructor function


2. Using the member function open( )

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 ( ):

This function is used to open a file for its operations.

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]

cout<<"Enter your name :";


cin>>name;
ofstream a("namefil.txt");
if(a.fail( ) )
{
cout<<"this file cannot be open";
exit(9);
}
n=strlen(name);
for(i=0;i<n;i++)
a.put(name[i]);
a.close();
}
get( ):
This member function is used to read a single character form a file.
Syntax:
obj.get(char_var);
Ex:
k.get(ch);
In the above example function get() reads a single character from a file and stores it into a character
type variable ch.

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.

Pointer offset calls


Offset Action
seekg(0,ios::beg) Go to start
seekg(0,ios::cur) Stay at the current position
seekg(0,ios::end) Go to the end-of-file
seekg(m,ios::beg) Move to(m+1)th byte in the file
seekg(m,ios::cur) Go forward by m bytes from the current position
seekg(-m,ios::cur) Go backward by m bytes from the current position
seekg(-m,ios::end) Go backward by m bytes from the end
Ex:
k.seekg(10,ios::beg)
The above statement moves the input file pointer to the 11th byte in the file.

Page 17
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Errors handling during file operations:


Common source of error:
1. A file we are trying to open for reading does not exist.
2. The file name used for a new file may already exist.
3. We may use an invalid file name.
4. We may try to perform an operation when the file is not opened for that purpose.
5. If the disk has no space to create a file.
Error handling functions:
eof(): If the end-of-file is encountered, this function will returns True otherwise returns False.
fail(): Returns True, when an input or output operation has failed.
bad(): Returns True if any unrecoverable error has occurred, otherwise it returns False.
good(): Return True if no error has occurred.
Command Line Argument:
Passing argument to the main() function is called command line argument. C++ provides a
feature to supply argument to the main() function. These arguments are supplied at the time of
invoking the program.
Ex:
C:\>exam data results
Here, exam is the name of the file containing the program to be executed, and data and results are
arguments to the main function.
General format:
main(int argc, char *argv[])
The first argument argc (argument counter) represents the number of arguments in the
command line. The second argument argv (argument vector) is an array of char type pointers to the
command-line arguments.
From the above example,
argv[0] ---> exam
argv[1] ---> data
argv[2] ---> results
Example:
#include<iostream.h>

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 Types:

Primitive data structures are predefined types of data, which are supported by the programming
language.

Abstract Data Types:

Page 19
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Non – primitive Data Type:

Non primitive data structures are not defined by the programming languages, but are derived
from primitive data structures.

Classification of 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.

2.1 Linear Data Structure:

In which data items are stored in sequence order.

Eg: Arrays, List, Stacks and Queue.

1 front rear

Page 20
……..

……..
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

2 top

………………………

array stack queue

Linked list

2.2 Non –Linear Data Structure:

In which order of data items is not presence.

Eg: Trees, Graphs.

Tree Graph

Operations of Data Structure:

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.

Inserting: Adding new element in the data structure is called insertion.

Deleting: Removing the record from the structure is called Deletion.

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.

One Dimensional Array:

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.

Representation of Linear Array in Memory:

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.

TRAVERSE (LA, LB, UB)

1. [Initialize counter] Set K:=LB


2. Repeat Steps 3 and 4 while K<=UB
3. Apply PROCESS to LA[K]

Page 22
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

4. Set K:= K+1


[End of step 2 loop]
5. Exit

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.

INSERT (LA, ITEM, K, N)

1. [Initalize counter] Set J:=N


2. Repeat step3 and step 4 while J>=K
3. [Move the Jth element downward] Set LA[J+1]:= LA[J]
4. [Decrement Counter] Set J:=J-1
[End of step 2 loop]
5. [Insert element] Set LA[K]:=ITEM
6. [Reset number of element n+1] Set N:=N+1
7. Exit

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.

DELETE (LA, K, N, ITEM)

1. Set ITEM:=LA[K]

Page 23
UNIT - 3 [PROGRAMMING IN C++ AND DATA STRUCTURES]

2. Repeat for J=K to N-1


Set LA [J]:=LA [J+1]
3. [Reset number of element as n-1] Set N:=N-1
4. Exit

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.

LINEARSEARCH (DATA, N, ITEM, LOC)

1. [Initialize counter] Set K:=1


2. Repeat Steps 3 and 4 while K<=N
3. IF ITEM = DATA[K]
Set LOC:=K
RETURN
4. Set K:= K+1
[End of step 2 loop]
5. LOC :=0
6. Exit

Multi-Dimensional Array:

Matrix (2-dimensional array), 3-dimensional arrays are two examples of multi-dimensional


arrays.

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]

1<=J<=m and 1<=K<=n

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.

a11 a12 a13 .. a1n

a21 a22 a23 .. a2n

……… ……. ……… ………..

am1 am2 am3 .. amn

Memory Representation of two-dimensional Array:

There are two conventions of storing any matrix in memory

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 a12 a13 a14

a21 a22 a23 a24

a31 a32 a33 a34

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

2. Three-Dimensional and n-dimensional array:

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.

Number of rows = x (number of elements in a column)


Number of columns=y (number of elements in a row)
Number of pages=z

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

You might also like