简体   繁体   中英

How can I make each scanf working without skip

I make the loop with gets and scanf. Actually I make the space for newline buffer. so I think each scanf works but when I input value to &books[ctr].cost compiler skip next 3 questions. I don't know why It work like this

books is structure variable

for (ctr = 0 ; ctr < 3 ; ctr++)
{
    printf("What is the name of the book #%d?\n", (ctr+1));
    gets(books[ctr].title);
    puts("Who is the author?  ");
    gets(books[ctr]. author);
    puts("How much did the book cost?  ");
    scanf("  $%f", &books[ctr].price);
    puts("How many pages in the book?  ");
    scanf("  %d", &books[ctr].pages);
    getchar( );
}
printf("\n\n Here is the collection of books : \n");
for (ctr = 0 ; ctr < 3 ; ctr ++)
{
    printf("#%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author);
    printf("\n It is %d pages and costs $%.2f", books[ctr].pages, books[ctr].price);
    printf("\n\n");
}

return 0;

}

First of all, two suggestions:

Use fgets() to take user input, and then convert to appropriate form using sscanf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM