Reputation: 2183
my code is
struct bat
{
char name[20];
int runs;
}b1;
void main()
{
char ch='y';
FILE *p;
p=fopen("details.dat","wb");
if(p==NULL)
{
printf("unable");
exit(0);
}
else
{
while ( ch == 'y' )
{
printf("enter details");
scanf("%s%d",b1.name,&b1.runs);
fwrite(&b1,sizeof(b1),1,p);
printf("do you want to eneter more");
scanf("%c",&ch);//it is not working
}
}
return 0;
}
if in place of scanf i use getche() then the code works perfectly and have desired output. but why it is not working with scanf()?
Upvotes: 1
Views: 171
Reputation: 344
scanf() works in a special way. When you use it to scan a character, all the keystrokes that user enters are stores in a buffer and repeatedly overwritten in the variable. Thus, if you enter 'y' and then press 'Enter key', scanf() will first store ascii value of 'y' in your character variable ch and then immediately overwrite it with ascii value of 'Enter key'.
So your condition ch=='y' fails because ch no longer holds 'y' but holds 'Enter key', causing your code to fail.
getch() or getche() is perfect to use in your case. Because it only accepts one keystroke from keyboard and stores it into the assigned variable without need to press Enter key. The only difference between these 2 functions is that getche() echoes the character on screen but getch() does not.
Hope this helps..
Upvotes: 1