I had difficulties while executing the following code. The variable 't' take a null value after complete one execution. The problem was solved by using getch() instead of scanf(). But i don't know why it's happening. Any explainations ? This is the program which didn't work.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char t;
void main()
{
while(1)
{
scanf("%c",&t);
printf("\nValue of t = %c",t);
printf("\nContinue (Y/N):");
char a=getche();
if(a=='n' || a=='N')
exit(0);
}
}
Now, this is the program which executes correctly.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char t;
void main()
{
while(1)
{
t=getch();
printf("\nValue of t = %c",t);
printf("\nContinue (Y/N):");
char a=getche();
if(a=='n' || a=='N')
exit(0);
}
}
When you read a character,
scanf("%c",&t);
there's a newline left behind in the input stream which causes the subsequent scanf() to skip input in the loop.
Note that getch()
is non-standard function. You can use getchar()
instead.
Or Change it to:
scanf(" %c",&t);
Notice the space in the format specifier which ensures all the whitespaces are skipped by scanf() before reading a character for %c
.