0

I'm attempting to write a small program that a user input book information in the "struct bookinfo" and then print what user write.

I accepted some advice in my past question. so I modified my program but It is still not working problem is that my program doesn't go to next question. If I put a character in integer variable It goes to next question but skip next question again!

here is my code

#include <stdio.h> 
#include <stdlib.h>

struct bookInfo {
    char title [40];
    char author [25];
    float price;
    int pages;
};

main()
{
    int ctr;
    struct bookInfo books[3];
    for (ctr = 0 ; ctr< 3; ctr++)
    {
        printf("What is the name of the book #%d?\n", (ctr+1));
        scanf( " %s", books[ctr]. title);
        puts("who is the author?");
        scanf(" %s", 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();
    }

output is Here.

What is the name of the book #1?
cosmos
who is the author?
kalcaygon
How much did the book cost?
14.99

and then, my program doesn't go to next question. but when I put a character, it go to next question. but skip next input like this

What is the name of the book #1?
cosmos
who is the author?
kalcaygon
How much did the book cost?
14.99





d
How many pages in the book?
who is the author?
How much did the book cost?
weltensturm
  • 2,164
  • 16
  • 17
  • Don't call `getchar`. And don't use the leading space in the `scanf` format strings. Neither are needed with the code you show. – Some programmer dude Nov 20 '20 at 08:56
  • you miss the `}` at the end of the code for close the `main() {` – Les Go Nov 20 '20 at 08:58
  • 1
    Maybe you have an extra space in your real scanf: `scanf("%f ", &books[ctr].price);` ?? After adding a final `}`, [your code works as is](https://ideone.com/IOsh0f) ... **but turn on and mind your compiler warnings!** – pmg Nov 20 '20 at 09:06
  • @pmg you saved my life...! Now I realized my fault thank you so much!! – Jeon Soo min Nov 20 '20 at 09:43
  • @JeonSoomin Your code is working fine in my system. There is no problem with `scanf( " %s", books[ctr]. title);` statement. But you will run into problems with `scanf( "%s ", books[ctr]. title);` – Krishna Kanth Yenumula Nov 20 '20 at 09:46
  • Please check this :https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string – Krishna Kanth Yenumula Nov 20 '20 at 09:48
  • Why is this question tagged with the **D** programming language? – Eljay Nov 22 '20 at 17:35

0 Answers0