Oop Unit IV
Oop Unit IV
Usage of Manipulators
Managing I/O console
C++ supports a rich set of I/O functions and
operations.
int code;
cin >> 4258D
The operator will read the characters upto 8 and the value 4258 is
assigned to code.
Overloaded Operators >> and <<
The general form for displaying data on screen is:
cout.put(‘x’); - What
Displays happen if this
the character x
statement is executed ?
cout.put(ch); - Displays the value of variable ch.
cout.put(68);
The statement will convert
68 to char value and display
character D.
getline() and write () Functions
The getline() function reads a whole line of text that ends
with a newline character.
This function can be invoked by using the object cin.
cout.write(line, size);
The first argument line represents the name of the
string to be displayed and the second argument size
indicates the number of characters to display.
Formatted I/O Operations
C++ supports a number of features that could be used
for formatting the output.
ios class functions and flags
Manipulators
cout.width(w);
Where w is the field width. The output will be printed in a field
of w characters wide at the right end of the field.
Eg: cout.width(5);
cout<< 543;
cout.width(5);
cout.precision(d);
Where d is the number of digits to the right of the decimal
point.
Eg: cout.precision(3);
cout.fill(ch);
Where ch represents the character which is used for filling the
unused positions.
Eg: cout.fill(‘*’);
cout.width(10);
Syntax:
cout.setf(arg1, arg2)
The arg1 is one of the formatting flags, specifying the action
required for the output.
The arg2 known as bit field specifies the group to which the
formatting flag belongs.
There are three bit fields and each has a group of format flags.
Formatting Flags, Bit-fields and
setf()
Formatting Flags, Bit-fields and
setf()
Consider the following segment of code:
cout.fill(‘*’);
cout.setf(ios::left, ios::adjustfield);
cout.width(15);
get (void).
argument.
cin >> c;
cin.get(c);
The first statement using the overloaded >> operator will skip
cout.write(s1,m).write(s2,n);
The above statement is used to concatenate two strings using
the write() function.
statement as:
iostream
file istream streambuf ostream
iostream
outf<<name;
cout<<“Enter item cost:”;
float cost;
cin >> cost;
inf.close();
return 0;
}
Output:
Enter item name: CD-ROM
Enter item cost: 250
int main()
{
ofstream fout;
fout.open(“Country”);
fout.close();
fout.open(“Capital”);
fout<<“Washington”;
fout<<“London”;
fout.close();
Opening Files Using open()
const int N=80;
char line[N];
ifstream fin;
fin.open(“Country”);
while(fin)
{
fin.getline(line, N);
cout<<line;
}
fin.close();
return 0;
}
Detecting End-of File
• Detection of the end-of-file condition is necessary
for preventing any further attempt to read data from
the file.
while(fin)
• An ifstream object return a value zero if any error
occurs in the file operation including the end-of-file
condition.
if(fin1.eof() != 0 ) { exit(1); }
• The eof() of ios class returns a non zero value if the
end-of-file condition is encountered and zero
otherwise.
Opening two files simultaneously
• When two or more files are used simultaneously
ie: when we want to merge two files into a single
file.
• In such case we create two separate input
streams for handling the two input files and one
output stream for handling the output file.
Opening two files simultaneously
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
int main()
{
const int size = 80;
char line[size];
ifstream fin1, fin2;
fin1.open(“country”);
fin2.open(“capital”);
Opening two files simultaneously
for(int i = 1; i <= 10; i++ )
{
if ( fin1.eof() ! = 0)
{
cout << “\n Exit from country \n ” ;
exit(1);
}
fin1.getline(line,size);
cout << “Capital of “ << line;
Opening two files simultaneously
if ( fin2.eof() ! = 0 )
{
cout << “ \n Exit from capital \n“ ;
exit(1);
}
fin2.getline(line, size);
cout << line << “\n”;
}
return 0;
}
Quiz 2
• What are default arguments?
▫ A default argument is a value provided in
function declaration that is automatically assigned
by the compiler if caller of the function doesn't
provide a value for the argument.
File Modes
• File mode specifies the purpose for which the file is
opened.
• File mode parameters:
▫ 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::nocreate //open fails if the file does not exists.
▫ ios::noreplace //open fails if the file already exists.
▫ ios::out //open file for writing only
▫ ios::trunc //delete the contents of file if it exists
File Pointers
• Each file has two associated pointers:
▫ get pointer or input pointer: used for reading the contents
of the file.
▫ put pointer or output pointer: used for writing to a given
file location.
int main()
{
char string[80];
cout << “Enter a string :\n ”;
cin >> string;
Put() & Get() functions
int len = strlen(string);
fstream file;
file.open(“Text”, ios::in | ios::out);
file.seekg(0);
Put() & Get() functions
char ch;
while(file)
{
file.get(ch);
cout << ch;
}
return 0;
}
Reading & Writing a class object
• C cannot handle user defined data types such as class
objects.
• C++ provides read() and write() functions to read and
write the objects directly.
• The length of the object is obtained using the sizeof
operator.
• This length represents the sum total of lengths of all data
members of the object.
Reading & Writing a class object
• Syntax:
▫ infile.read ((char *) & V, sizeof (V));
▫ outfile.write ((char *) & V, sizeof (V));
• The first argument is the address of the variable V.
• The second is the length of that variable in bytes.
• The address of the variable must type cast to char *
(ie: pointer to character type).
Example
#include<iostream.h>
#include<fstream.h>
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void);
};
Example cont…
void inventory :: readdata(void)
{
cout<<“Enter name:”;
cin>> name;
cout<<“Enter code:”;
cin>>code;
cout<<“Enter cost:”;
cin>> cost;
}
void inventory :: writedata(void)
{
cout<<name;
cout<<code;
cout<<cost;
}
Example cont…
int main()
{
inventory item[3];
fstream file;
file.open(“Stock.dat”, ios::in | ios::out);
cout<<“Enter the details for three items:”;
for(int i=0; i<3;i++)
{
item[i].readdata();
file.write((char *) & item[i], sizeof(item[i]));
}
Example cont…
file.seekg(0);
for(i=0;i<3;i++)
{
file.read((char *) & item[i], sizeof(item[i]));
item[i].writedata();
}
file.close();
return 0;
}
Updating a File: Random Access
• Updating is a routine task in the maintenance of
any data file.
• The updating would include one or more of the
following tasks:
▫ Displaying the contents of a file.
▫ Modifying an existing item.
▫ Adding a new item.
▫ Deleting an existing item.
Updating a File: Random Access
• The size of each object can be obtained using the
statement:
int obj_len = sizeof(object);
• The location of a desired object (say m) is
obtained as:
int location = m * obj_len;
• The total number of objects in a file can be
obtained by using object length as:
int n = file_size / obj_len;
Updating a File: Random Access
#include<iostream.h>
#include<fstream.h>
class inventory
{
char name[10];
int code;
float cost;
public:
void getdata(void)
{
cout<<“Enter name : ” ; cin>> name;
cout<<“Enter code : ” ; cin>>code;
cout<<“Enter cost : ” ; cin>> cost;
}
Updating a File: Random Access
void putdata(void)
{
cout<<name;
cout<<code;
cout<<cost;
}
};
int main()
{
inventory item;
fstream inoutfile;
inoutfile.open(“stock.dat”, ios::ate | ios::in | ios::out|
ios::binary);
inoutfile.seekg(0, ios::beg);
Updating a File: Random Access
while(inoutfile.read((char * ) & item, sizeof item))
{
item.putdata();
}
inoutfile.clear(); //turn off EOF flag
cout<<“Add an item:”;
item.getdata();
inoutfile.write((char * ) & item, sizeof item);
inoutfile.seekg(0);
while(inoutfile.read((char * ) & item, sizeof item))
{
item.putdata();
}
Updating a File: Random Access
int last = inoutfile.tellg(); // finds the no. of objects
int n = last/sizeof(item);
cout<<“Number of objects:”<<n;
cout<<“Enter the object number to be updated:”;
int object;
cin>> object;
int location = (object-1)* sizeof(item);
inoutfile.seekp(location);
return 0;
}
Updating a File: Random Access
Output:
current contents of stock:
AA 11 100
BB 22 200
CC 33 300
Add an item:
Enter name: DD
Enter code: 44
Enter cost: 400
Updating a File: Random Access
Contents of Appended file:
AA 11 100
BB 22 200
CC 33 300
DD 44 400
Number of objects: 4
Enter the object to be updated: 4
Enter new values for object:
Enter name: EE
Enter code: 55
Enter cost: 500
Contents of updated file:
AA 11 100
BB 22 200
CC 33 300
EE 55 500
Error Handling During File Operations
• Following conditions may arise while dealing with
files:
▫ A file which we are attempting to open for reading does
not exists.
▫ The file name used for a new file may already exists.
▫ We may attempt an invalid operation such as reading
past the end-of-file.
▫ There may not be any space in the disk for storing more
data.
▫ We may use invalid file name.
▫ We may attempt to perform an operation when the file is
not opened for that purpose.
Error Handling During File Operations
• The ios class supports several member functions that can
be used to read the status recorded in a file stream.
Function Return value and meaning
eof( ) Returns true (non zero value) if end-of-file is encountered
while reading otherwise returns false (zero).