I have below C code.
#include<stdio.h>
int main()
{
//Declaring structure book.
struct book
{
char name;
float price;
int pages;
};
struct book b[5];
int i;
//Below loop takes the info if 5 books from user
for (i=0; i<5; i++)
{
printf("Enter name, price, and pages: ");
fflush( stdin );
scanf("%c%f%d",&b[i].name,&b[i].price,&b[i].pages);
}
return 0;
}
However when I compile and run, something strange happens.
-bash-4.1$ ./a.out
Enter name, price, and pages: A 23 34
Enter name, price, and pages: B 34 54
Enter name, price, and pages: Enter name, price, and pages: C 56 78
Enter name, price, and pages: -bash-4.1$
You can see that when i = 2, scanf() does NOT wait for keyboard. Then when i = 3, scanf() waits for keyboard input. Again in i=4, scanf() does NOT wait for keyboard input.
I guess I have used
fflush(stdin);
in the correct place. I don't want the return key to be in the buffer in the next scanf().
To debug, i tried not to use fflush(stdin) and see what heppens. But even without the fflush(stdin), same thing happens when i run the program. So I guess fflush(stdin) is not causing this problem.
Please anyone point out, where my program is going wrong?
Thanks.
fflush( stdin );
it's for stdout 2.scanf(" %c %f %d",&b[i].name,&b[i].price,&b[i].pages);
Space and fixed – Rizier123" %c %f %d"
? Since there are spaces between the numbers. – Tim Časprintf
statements would come in handy here. Basic debugging. – user3920237