If you like my posts please leave a comment.

Tuesday, August 7, 2012

Library Functions: getch( ) and putch() Functions


Character I/O Functions:


The functions getch() and putch() also character I/O functions, defined in conio.h

getch():      

getch( )  function receives a character from the standard input as soon as a character key is pressed. User need not to press Enter key to enter a data item. As soon as key is pressed data is brought in to your program. It does not echo the character on the screen as it receives them. Now if you compare the same function with get() we will find that, in case of get() function, entered character can be seen on the screen and can be erased with backspace if required because it was a buffered character output function.
So, when you want that your program should respond as soon as a key is pressed from the keyboard you should use getch(). You can also getche() function. It is a modified version of getch(). This is also basically non-buffered character input function but it echoes the character input. In this case also user needs not to press Enter key to send data to your program.

Syntax: char_variable = getch();
Example:
char ch;
ch = getch();

putch():

            putch() function does the same work of put() function. It prints a single character at a time to the standard output device (Screen). Except screen and modem almost all other output devices are buffered output devices. putch() function can not be used with cout or with any other user-defined output stream object. As it is a non-buffered function. If you use it with cout, you will get error message – putch is not a member of ostream-withassign and if it is used with any other user-defined output stream object as shown below:

Syntax: putch(char_variable);
Example:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<fstream.h>
void main()
{
clrscr();
char string[50];
cout<<"\n Enter an string to write in a file";
gets(string);
fstream FILE;
FILE.open("MYTEXT.TXT",ios::app);
     for(int i=0;string[i]!='\0';i++)
     {
      FILE.putch(string[i]);/* Here it is illegal to use putch function with a user-define output stream object which represents a disk file*/
     }
FILE.close();
getch();
}

You will get the error message – “putch is not a member of fstream”.

Note**
Both gehtch() and putch() are not ANSI C standard functions.

No comments:

Post a Comment