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.

3
  • 2
    What exactly "goes wrong"? And don't use gets but fgets instead! Commented Oct 21, 2015 at 13:45
  • 1
    scanf("%d" --> scanf("%d%*c" Commented Oct 21, 2015 at 13:55
  • it stop taking string Commented Oct 21, 2015 at 13:56

2 Answers 2

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 .

Sign up to request clarification or add additional context in comments.

2 Comments

it works perfectly. can you please explain how is this while loop working?
@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 .
0

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

fflush(stdin)

1 Comment

Never knew that. Thanks a lot @chux

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.