Sunday 20 May 2012

Differentiate between getch(), getche(), and getchar().


The two functions getch() and getche() are very similar, as they respond without pressing the Enter key. The difference is that with the function getche() the echo of the pressed key is displayed on the screen (the letter “e” stands for “echo”), but with the function getch(), there is no echoing. The program shown in the figure 1 demonstrates the use of both functions. Similarly, the program shown in the figure 3 demonstrate the difference between getche(), getch(), and getchar() function.
getchar() function reads one character from the keyboard after the new line character is received, when we press Enter key. The program shown in figure 2 demonstrates the use of the function getchar(). It begins with declaring an integer variable “ascii”, then the function itself is assigned to this variable.
This means that the character received by the function will be contained in the variable “ascii”. The first printf() function displays the contents of the variable “ascii” in the character format (%c) preceded by the string “the character”. The second printf() function displays the same variable in the decimal format (%d) preceded by the string corresponds to the ASCII.
Figure 1
//demonstration of getche() and getch() function
main()
{
int option;
printf("\nmake a choice and press a number : ");
option=getche();
printf("\nmake a choice and press a number : ");
option=getch();
}
Figure 2
//demonstration of getchar() function
main()
{
int ascii;
printf("\nType a character and press ENTER : ");
ascii=getchar();
printf("The character %c ",ascii);
printf("Corresponding to the ASCII %d ",ascii);
}

Figure 3
//demonstration of getch(), getche() and getchar() function
main()
{
char ch;
printf("Press any key to continue ");
getch();
printf("\nType any character ");
ch=getche();
printf("\nType any character ");
getchar();
}

No comments:

Post a Comment