Home > OS >  Can anyone tell me what's wrong in my code given below?
Can anyone tell me what's wrong in my code given below?

Time:03-04

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related