Unable to find bug in this C program
I'm unable to find bug in this C program.
#include <stdio.h>
int main()
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b[3] ;
int i ; int k;
for ( i = 0 ; i <= 2 ; i++ )
{
printf ( "\nEnter name, price and pages: " ) ;
k = scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 2 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
//getch();
return 0;
}
run time:
Enter name, price and pages: a 1 1
Enter name, price and pages: b 2 2
Enter name, price and pages:
a 1.000000 1
7922540190797673100000000000000000.000000 4200368
b 2.000000 2
I wanted to give a 1 1
, b 2 2
, c 3 3
as my开发者_开发百科 inputs for each scanfs but it didn't wait for my input in 3rd scanf. Why so? and why did it read my 2nd time input into 3rd elementof array?
Add a getchar()
after your scanf()
for ( i = 0 ; i <= 2 ; i++ )
{
printf ( "\nEnter name, price and pages: " ) ;
k = scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
getchar(); //will clear the buffer
}
P.S: Don't use scanf()
for char
entry.
Unlike the other specifiers, %c when used with scanf does not ignore whitespace. You probably want to make the name fields strings in any case:
#include <stdio.h>
int main()
{
struct book
{
char name[10] ; // or some suitable size
float price ;
int pages ;
} ;
struct book b[3] ;
int i ; int k;
for ( i = 0 ; i <= 2 ; i++ )
{
printf ( "\nEnter name, price and pages: " ) ;
k = scanf ( "%s %f %d", b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 2 ; i++ )
printf ( "\n%s %f %d", b[i].name, b[i].price, b[i].pages ) ;
return 0;
}
You can add .fflush(stdin);
before your scanf.
It turns out that you should not use fflush
on stdin
because fflush
is only defined to work on output streams. In other words fflush
has undefined behaviour on input streams.
int fflush(FILE *ostream);
an extract from the C standard says:
ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
精彩评论