Developed By : Ms. K. M. Sanghavi - · PDF fileWe can also create manipulators that could...

25
Developed By : Ms. K. M. Sanghavi

Transcript of Developed By : Ms. K. M. Sanghavi - · PDF fileWe can also create manipulators that could...

Developed By : Ms. K. M. Sanghavi

Designing Our Own Manipulators

We can design our own manipulators for certain special purpose.The general form for creating a manipulator without any arguments is:

ostream & manipulator(ostream & output) { ………… …………(code) ………… return output } Here the manipulator is the name of the manipulator under creation.

The following function defines a manipulator called unit that dispalys”inches”:

ostream & unit(ostream &output)

{

output<<”inches”;

return output;

}

The statement

cout<<36<<unit;

will produce the following output

36 inches

We can also create manipulators that could represent a sequence of operations.

Example:

ostream & show(ostream & output)

{

output.setf(ios::showpoint);

output.setf(ios::showpos);

output<<setw(10);

return output;

}

Program illustrates the creation and use of the user-defined manipulators. The program creates two manipulators called currency and form which are used in the main program.

#include<iostream.h>

#include<iomanip.h>

ostream & currency(ostream & output)

{

output<<”Rs”;

return output;

}

ostream& form(ostream & output) {

output.setf(ios::showpos); output.setf(ios::showpoint); output.fill(‘*’); output.precision(2); output<<setiosflags(ios::fixed)<<setw(10); return output;

} int main() {

cout<<currency <<form<<7864.5; return 0;

}

The output of Program would be:

Rs**+7864.50

Stream Errors

• bool ios::good() : returns true if no error

• bool ios::bad() : returns true if invalid read/write

• bool ios::eof() : returns true if end of file reach

• bool ios::fail() : returns true if input operation fails

• void ios::clear() : clears all the flags

int main() { int num; bool valid = false; while (!valid) { valid = true; //Assume the cin will be an integer. cout << "Enter an integer value: " << endl; cin >> num; if(cin.fail()) //cin.fail() checks to see if the value in the cin //stream is the correct type, if not it returns true, //false otherwise. { cin.clear(); //This corrects the stream. cin.ignore(); //This skips the left over stream data. cout << "Please enter an Integer only." << endl; valid = false; //The cin was not an integer so try again. } }

cout << "You entered: " << num << endl; system("PAUSE"); return 0; }

File I/O Streams

Stream Description

ifstream Reads from files

ofstream Writes on files

fstream Read & Write From/To files

To perform File I/o We include <fstream.h> in the program

ifstream

Input file stream Class

open() is a member function of the class ifstream

Inherited functions of ifstream class, from the class istream are

• get()

• getline()

• read()

• seekg()

• tellg()

ofstream

Output file stream Class

open() is a member function of the class ofstream

Inherited functions of ofstream class, from the class ostream are

• put()

• write()

• seekp()

• tellp()

File Handling Classes

File Handling Classes

Use method “open()”

Or immediately in the constructor (the natural and preferred way).

Opening a File

copyrights © Elhanan Borenstein

17

Opening a File

• Before data can be written to or read from a file, the file must be opened.

ifstream inputFile;

inputFile.open(“customer.dat”);

Another Syntax • void open(const char* filename, int mode);

filename – file to open (full path or local)

mode – how to open (one or more of the following – using | )

File Handling Classes

Modes can be

ios::app – append

ios::ate – open with marker at the end of the file

ios::in / ios::out – (the defaults of ifstream and ofstream)

ios:nocreate / ios::noreplace – open only if the file exists / doesn’t exist

ios::trunc – open an empty file

ios::binary – open a binary file (default is textual)

Don’t forget to close the file using the method “close()”

19

Opening a File at Declaration

fstream f;

f.open(“names.dat”, ios::in | ios::out |ios:app);

20

Testing for Open Errors

dataFile.open(“cust.dat”, ios::in);

if (!dataFile)

{

cout << “Error opening file.\n”;

}

is_open() – Checking whether the file was open correctly. (for compatibility with C, the operator ! was overloaded).

rd_state() – returns a variable with one or more (check with AND) of the following options:

ios::goodbit – OK

ios::eofbit – marker on EOF

ios::failbit – illegal action, but alright to continue

ios:badbit – corrupted file, cannot be used.

We can also access the bit we wish to check with eof(), good(), fail(), bad().

clear() is used to clear the status bits (after they were checked).

Querying a File

copyrights © Elhanan Borenstein

File Handling Classes

22

Another way to Test for Open Errors

f.open(“cust.dat”, ios::in);

if (f.fail())

{

cout << “Error opening file.\n”;

}

23

Detecting the End of a File

• The eof() member function reports when the end of a file has been encountered.

if (f.eof())

f.close();

seekg() / seekp() – moving the reading (get) / writing (put) marker

two parameters: offset and anchor

tellg() / tellp() – getting the position of the reading (get) / writing (put) marker

Moving within the File

copyrights © Elhanan Borenstein

File Handling Pointers

To write:

put() – writing single character

<< operator – writing an object

To read:

get() – reading a single character of a buffer

getline() – reading a single line

>> operator – reading a object

Reading /Writing from/to Textual Files

#include <fstream.h>

main()

{

// Writing to file

ofstream OutFile("my_file.txt");

OutFile<<"Hello "<<5<<endl;

OutFile.close();

int number;

char dummy[15];

// Reading from file

ifstream InFile("my_file.txt");

InFile>>dummy>>number;

InFile.seekg(0);

InFile.getline(dummy, sizeof(dummy));

InFile.close();

}

File Handling Classes