0
#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.

2 Answers2

1

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 .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • it works perfectly. can you please explain how is this while loop working? – Tawhidur Rahman Tanim Oct 21 '15 at 16:16
  • @TawhidurRahmanTanim Value returned from `getchar` is assigned to `c` . If value returned and stored in `c` is `EOF` or `'\n'` loop exits and if not then loop extracted ,until `EOF` or `'\n'` is encountered . In this way if `'\n'` is present in `stdin` it is read from it . – ameyCU Oct 21 '15 at 16:20
0

After scanf include this line to remove the newline character remaining in stdin

fflush(stdin)