0

I want to take input from user using structure. So I'm using the code like below. But it's not printing the values which I'm entering. Can anyone help me?

#include <stdio.h>

int main()
{
    struct book
    {
        char name;
        float price;
        int pages;        
    };

    struct book b1, b2;
    printf("Enter the Name, Price and Pages of Book 1: ");
    scanf("%c %f %d", &b1.name, &b1.price, &b1.pages);
    printf("Enter the Name, Price and Pages of Book 2: ");
    scanf("%c %f %d", &b2.name, &b2.price, &b2.pages);
    printf("Here is the data you've entered: \n");
    printf("Name: %c Price: %f Pages: %d\n", b1.name, b1.price, b1.pages);
    printf("Name: %c Price: %f Pages: %d\n", b2.name, b2.price, b2.pages);
    
    return 0;
}

But I'm not getting the output as desired. My Output Image

  • 1
    `"%c ...` --> `" %c ...`. Add space. Check return value of `scanf()`. – chux - Reinstate Monica Mar 04 '22 at 05:30
  • well for a start you cannot store a name in a single character. Work on that first – pm100 Mar 04 '22 at 05:30
  • also a huge clue will come from looking at the value returned by scanf, it will tell you if it read the correct data, yours should return 3, are they? – pm100 Mar 04 '22 at 05:31
  • @chux-ReinstateMonica Thanks a lot. I added the space in starting and it returned the perfect output. Can you tell why it is necessary to add a space in start? – Rushabh Laddha Mar 04 '22 at 05:46
  • @pm100 Yes I know that I cannot store the name in single char. But as I just started the structure chapter, I don't want to complicate the program so I decided to use single char. Thank You for your response. – Rushabh Laddha Mar 04 '22 at 05:49

1 Answers1

0

Your question is similar to this one: scanf() leaves the newline character in the buffer

And can be corrected like this:


#include <stdio.h>

int main()
{
    struct book
    {
        char name;
        float price;
        int pages;
    };
    char buffer[255];

    struct book b1, b2;
    printf("Enter the Name, Price and Pages of Book 1: ");
    scanf(" %c %f %d", &b1.name, &b1.price, &b1.pages);
    printf("Enter the Name, Price and Pages of Book 2: ");
    scanf(" %c %f %d", &b2.name, &b2.price, &b2.pages);
    printf("Here is the data you've entered: \n");
    printf("Name: %c Price: %f Pages: %d\n", b1.name, b1.price, b1.pages);
    printf("Name: %c Price: %f Pages: %d\n", b2.name, b2.price, b2.pages);

    return 0;
}

Note the leading space before the %c input.

Alex Nicolaou
  • 217
  • 1
  • 4