Reputation: 29
#include <stdio.h>
struct book
{
char name[1000];
int price;
};
int main()
{
struct book ct1[5];
int i;
for (i = 0; i < 5; i++)
{
printf("Please Enter %d Number Book Name: ",i+1);
gets(ct1[i].name);
printf("Price: ");
scanf("%d", &ct1[i].price);
}
for (i = 0; i < 5; i++)
{
printf("%d Nuumber Book's name and price : \n",i+1);
printf("%s = %d\n", ct1[i].name, ct1[i].price);
}
return 0;
}
I write this code to take book names and price and to print it.
like
input: Please Enter 1 Number Book Name: Sherlock
price:100
...................
...................
output:
Number Book's name and price: Sherlock = 100
.................
................
but it taking input like this Please Enter 1 Number Book Name: sherlock holmes
price: 100
Please Enter 2 Number Book Name: price: ........
first time it is correct but from the second time something goes wrong. please help me.
Upvotes: 0
Views: 80
Reputation: 88
After scanf
include this line to remove the newline character remaining in stdin
fflush(stdin)
Upvotes: 0
Reputation: 16607
First of all stop using gets
, use fgets
instead -
fgets(ct1[i].name,sizeof ct1[i].name,stdin );
And after your scanf
you can do this -
while((c=getchar())!=EOF && c!='\n');
declare c
as int
before for
loop .
This is to remove '\n'
from stdin
which remains after scanf
in each iteration and causes fgets
to return .
Upvotes: 1