Saturday, April 6, 2013

getch in c

getch in c language: getch function prompts the user to press a character and that character is not printed on screen, getch header file is conio.h.

C programming code for getch

/* getch in c example */
#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("Waiting for a character to be pressed from the keyboard to exit.\n");
 
   getch();
   return 0;
}
When you will run this program, the program will exit only when you press a character, note that we are talking about a character so try pressing numlock, shift key etc (program will not exit if you press these keys) as these are not characters. Also try the above program by removing getch(), in this case program will exit without waiting for a character being pressed from keyboard.

How to use getch in c++

#include<iostream.h>
#include<conio.h>
 
main()
{
   cout << "Enter a character";
   getch();
}

getch in Dev C++ compiler

getch library function works in dev c++ compiler, also note that it doesn't support all functions of conio.h as turbo c does.

getchar in c

#include<stdio.h>
 
main()
{
   int c;
 
   c = getchar();
 
   putchar(c);
 
   return 0;
}
Common use of getch is that you can view the output (if any) of your program without having to open the output window if you are using turbo c compiler or if you are not running your program from command prompt.

No comments:

Post a Comment