Sunday 9 October 2011

Explain I/O manipulators and give examples

Explain I/O manipulators and give examples:


                                                                    MANIPULATORS


Custom manipulators( i.e user defined manipulators)

In addition to overloading the insertion and extraction operators, you can further customize c++’s I/O system by creating your own manipulator function Custom manipulators are important for two main reasons. First, a manipulator can consolidate a sequence of several separate I/O operations. For example, it is not uncommon to have situations in which the same sequence of I/O operations occurs frequently within a program. In these cases you can use a custom manipulator to perform these actions, thus simplifying your source code and preventing accidental errors. Second, a custom manipulator can be important when you need to perform I/O operations on a nonstandard device. For example, you could use a manipulator to send control codes to a special type of printer or an optical recognition system.
Custom manipulators are a feature of C++ that supports OOP, but they can also benefit programs that aren’t object oriented. As you will see, custom manipulators can help make any I/O-intensive program clearer and more efficient.

Type of Manipulators:

As you know, there are two basic types of manipulators:
(1)   operate on input streams
(2)   operate on output streams

In addition to these two bread categories, there is a secondary division: those manipulators that take an argument and those that don’t. There are some significant differences between the way a parameterless manipulators and a parameterized manipulator are created. Further, creating parameterized manipulators is substantially more difficult than creating parameterless ones and is beyond the scope of this book.  However, writing your own parameterless manipulators is quite easy and is examined here.

All parameterless manipulator output functions have this syntax:


ostream &manip-name(ostream &stream)
{
  //code
  return(stream);
}

Here manip-name is the name of the manipulator and stream is a reference to the involing stream. A reference to the stream is returned. This is necessary if a manipulator is used as part of a larger I/O expression. It is important to understand that even thought the manipulator has as its single parameter(argument) a reference to the stream upon which it is operating, no parameter(argument) is used when the manipulator is called in an output operation.
All parameterless input manipulator functions have this syntax:

istream &manip-name(ostream &stream)
{
  //code
  return(stream);
}
An input manipulator receives a reference to the stream on which it was invoked. This stream must be returned by the manipulator.

It is very important that you manipulators return a reference to the invoking stream. If this is not done, your manipulators cannot be used in a sequence of input or output operations.

Examples:
1. as a simple first example, the following program creates a manipulator called setup() that sets the field width to 10, the precision to 4, and the fill character to *.

#include<iostream.h>
#include<conio.h>
ostream &setup(ostream &stream)
{
 stream.width(10);
 stream.fill(‘*’);
 return(stream);
}
void main()
{
  cout<<setup<<123.123456;
  return(0);
}

In the above prog, setup is used as part of an I/O expression in the same way that any of the predefined manipulators would be used.

2. Custom manipulators (User Defined Manipulators)


c++ streams can also work well with the user -defined manipulators.Hence the user can 
design their own manipulators .Hence the user can design their own manipulators to control
the appearance of the output depending upon their need.
the gereral syntax of creating a user-defined manipulator is as follows



ostream &manipulator (ostream &output,argument_if_any)
{
//mainpulator code
.
return output;
}


 need not be complex to be useful. For example, the simple manipulators atn() and note(), given below, it gives a output frequently used words or phrases. (instead of atn(), note() we can write any name)
#include<iostream.h>
#include<conio.h>
//attention
ostream &atn(ostream &stream)
{
 stream<<”Attention:”;
 return(stream);
}

//Please note:
ostream &note(ostream &stream)
{
 stream<<”Please note:”;
 return(stream);
}
void main()
{
  cout<<atn<<”checking squads are coming! \n”;
  cout<<note<<”handover your slip papers to avoid malpractice\n”;
}
....................................................................................................................................................................
Ex2:

#include<iostream.h>
ostream &digit(ostream&digit (ostream&num
{
num<<" "<< flush;
}
void main()
{
int a= 10,b=20;
cout<<a<<digit<<b<<endi;
}
Output:
10       20




Even though they are simple, if used frequently, these manipulators save you from some difficult typing frequently.

3. This program creates the getpass() input manipulator, which rings the bell and then prompts for a password:
#include<iostream.h>
#include<conio.h>
//a simple input manipulator
istream &getpass(istream &stream)
{
 cout<<”\a”; //it sounds a bell
 cout<<”enter your password:\n”;
 return(stream);
}

void main()
{
 char pw[80];
 clrscr();
 do
 {
   cin>>getpass>>pw;
 }while(strcmp(pw,”password”;
 cout<<”Logon complete\n”;
}

1. Creates an output manipulator that displays the current system time and date. Call this manipulator td().
2. Creates an output manipulator called sethex() that sets output to hexadecimal and turns on the uppercase and showbase flags. Also, create an output manipulator called reset() that undoes the changes made by sethex().
3. Create an input manipulator called skipchar() that reads and ignores the next ten characters from the input stream.

4. What are the input output manipulators?

flush                : output manipulator it flushes the stream
endl                 : output manipulator it inserts a newline and flushes the buffer
ends                : output manipulator that inserts end of string character.
ws                    : input manipulator that skips white spaces.
uppercase       :output manipulator that replaces certain lowercase letters with their uppercase equivalents.
dec                  : is an i/o manipulator that converts integers to/from decimal notation.
hex                  : is an i/o manipulator that converts integers to/from hexadecimal notation
showbase        :  is an output manipulator that generates a prefix indicating the numeric base of an integer.
showpoint        : is an output manipulator that always generates a decimal-point for floating-point values.
boolalpha        : is an i/o manipulator that puts bool(Boolean) values in alphabetic format.



Explain about Input/Output with files

C++ provides the following classes to perform output and input of characters to/from files:

  • ofstream: Stream class to write on files
  • ifstream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream. We have already used
objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream.
Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file
streams the same way we are already used to use cin and cout, with the only difference that we have to associate
these streams with physical files. Let's see an example:
Define 
(i)put() (ii)get()

ans:
ostream::put
Writes the character c to the output buffer at the current put position and increases the put pointer to point to the next character.


syntax: ostream& put ( char c );
Character to write.
Example:

// typewriter
#include <iostream>
#include <fstream>
 
void main () 
{
 
  char ch;
  ofstream outfile ("test.txt");
 
  do 
  {
    ch=cin.get();
    outfile.put (ch);
  } while (ch!='.');
 
  getch();
}



explain  the following file I/O functions.
ans: 
(i)Open a file :


    /* The first operation generally performed on an object of one of these classes is to associate it to a real file. This
procedure is known as to open a file.*/
 An open file is represented within a program by a stream object and any input or output operation
performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open():
 syntax:  open (filename, mode);

/* 

  • Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, 
  • and mode is an optional parameter with a combination of the
following flags:





ios::in
Open for input operations.
ios::out
Open for output operations.
ios::binary
Open in binary mode.
ios::ate
Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::app
All output operations are performed at the end of the file, appending the content to the current content

of the file. This flag can only be used in streams open for output-only operations.
ios::trunk
If the file opened for output operations already existed before, its previous content is deleted and
replaced by the new one.

  • All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open()ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); 
  • Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:




CLASS
Default mode parameter
ofstream
Ios::out
ifstream
Ios::in
fstream
Ios::in | ios::out
/* | means bitwise operator OR */



For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.




(ii) Closing a file


When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

Syntax: rajfile.close();

Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the destructor automatically calls the
member function close().


(iii) Reading and writing :

File streams include two member functions specifically designed to input and output binary data sequentially:
write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a
member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their

Syntax: (or prototypes) 
write ( memory_block, size );
read ( memory_block, size );

Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where
the read data elements are stored or from where the data elements to be written are taken. The size parameter is
an integer value that specifies the number of characters to be read or written from/to the memory block.



No comments:

Post a Comment