Thursday, March 17, 2011

getche() vs getchar()........

let us try to u nderstand this by the help of an example.....just write a program to enter you name and print that on the screen.....everyone can write that program so easily.....

void main()
{
char c[15];
printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
getche();
}

output:
enter yourname:milan
your name is :milan

this runs fine ,and wait for the character on the getche() function call as expected....

Now,chnage the getche() to getchar()

void main()
{
char c[15];
printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
getchar();
}

after running with getchar() you willl find that it does not wait for the character and output screen goes away....
why it is so????
Explanation:
this happens because the mechanism of getche() and getchar() is different..
1.)getche() directly takes the input directly from the input stream and getchar() reads that from the input buffer....
2.)getche() does not wait for the enter key and getchar() wait for hte enter key....

Now we enter our name and press enter that enter goes as the input for the getchar() function....let us prove this.......
void main()
{
char c[15],d;
 printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
d=getchar();
printf("the ASCII value of enter key is %d and it is true",d);
getch();
}

output:
enter your name:milan
your name is:milan
the ASCII value of enter key is 10 and it is true.....

so u can see the enter pressed after entering the name goes as the input to the getchar() function.....

solution to this problem:
use the fflush function withe the input stream from where you are reading the data that is generally stdin (standard input).....it will clear the input stream buffer and now getchar() will wait ......
check this:
void main()
{
char c[15];
printf("enter your name:");
scanf("%s",c);
printf("\nyour name is:%s",c);
fflush(stdin);
getchar();
}


another example which proves that getchar() waits for the enter key and takes the first character int the buffer after pressing the enter........

#include<stdio.h>
#include<conio.h>
void main()
{
char a,b,c;
clrscr();
printf("Enter a charater-->");
a=getche();
printf("\nThe character pressed is :%c",a);
printf("\nNow enter the another charater-->");
b=getchar();
printf("Now the character pressed is:%c",b);
getch();
}

output:
Enter a character-->m /*here you can enter only one character coz getch directly interact with input device*/
The character pressed is:m
Now enter the another character-->milan  /*here you can ebter any number of character ,all get stored int he buffer and after pressing enter the first character is taken as the input to the gatchar()*/
Now the character pressed is:m