-4

I have notice that only first scanf from for loop is asked and rest of them skip scanf request.

int main()
{
    int c = 0;
    int i;

    struct book
    {
        char name[20];
        float price;
        int page;
    };

    printf("\n enter number of book to add\n ");
    scanf("%d", &c);
    struct book b[c];
    printf("\n book details  \n ");

    for (i = 1; i < c; i++)
    {
        printf("\n enter name for book %d", i);
        scanf(" %c", &b[i].name);
        fflush(stdin);
        printf("\n enter price for book %d", i);
        scanf(" %f", &b[i].price);
        fflush(stdin);
        printf("\n enter page for book %d", i);
        scanf(" %d", &b[i].page);
    }
}

OUTPUT

enter number of book to add 3

book details enter name for book 1james

enter price for book 1

enter page for book 1

enter name for book 2

enter price for book 2

enter page for book 2

mch
  • 9,424
  • 2
  • 28
  • 42
simon bremson
  • 93
  • 2
  • 10
  • 3
    Welcome to StackOverflow! Your question doesn't seem to have an actual question in it at the moment, you'll likely receive more help if you edit it. – Sean Apr 05 '18 at 13:47
  • 1
    Please note that calling `fflush` in an input-only stream (like `stdin`) is explicitly marked as *undefined behavior* in the C specification. Some libraries implement it as an extension of the language, but it's not portable and not something you really should do. – Some programmer dude Apr 05 '18 at 13:49
  • 1
    [How to read / parse input in C? The FAQ](https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq). – Lundin Apr 05 '18 at 13:49
  • 2
    As for your problem, think about what you attempt to read for the name! – Some programmer dude Apr 05 '18 at 13:50
  • Rule of thumb: scanf is confusing, and should not be used while learning the language. If you invest time learning scanf, you're not learning C; your're learning the scanf formatting language. – William Pursell Apr 05 '18 at 14:22

2 Answers2

3

This:

scanf(" %c",&b[i].name);

looks super wrong, it reads a single character which doesn't make sense as a name, and also doesn't match your usage.

You likely meant:

scanf("%19s", b[i].name);

but that's bad too, since %s will stop at whitespace and book titles can have multiple words. Better to use fgets() to get full lines, then parse them.

Make sure you check the return value of all scanf() calls before relying on them having succeeded! I/O is brittle and can fail.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Correct your below statement:-

scanf(" %c",&b[i].name);  to scanf("%19s",b[i].name);

Because this is a string not a character variable. To read a string you need to use %s but not %c. We use %c to read a single character only. For example

char sex;

scanf(" %c",&sex);

Also in the case of an array we don't need to provide &, array itself behave like a pointer in C/C++.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17