Varun Rustgi
Varun Rustgi

Reputation: 21

Not able to print char element of a strucure variable

#include<stdio.h>

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

    struct book b1, b2, b3;
    char ch;
    printf("\nEnter the info of the books:\n");

    while ((ch = getchar()) == '\n' && ch != EOF) { }

    scanf_s("%c", &b1.name, sizeof(char));
    scanf_s("%f", &b1.price, sizeof(float));
    scanf_s("%d", &b1.pages, sizeof(int));

    while ((ch = getchar()) != '\n' && ch != EOF) {}

    scanf_s("%c", &b2.name, 1);
    scanf_s("%f", &b2.price, sizeof(float));
    scanf_s("%d", &b2.pages, sizeof(int));

    while ((ch = getchar()) != '\n' && ch != EOF) {}

    scanf_s("%c", &b3.name, 1);
    scanf_s("%f", &b3.price, sizeof(float));
    scanf_s("%d", &b3.pages, sizeof(int));

    printf("\n%c %f %d", b1.name, b1.price, b1.pages);
    printf("\n%c %f %d", b2.name, b2.price, b2.pages);
    printf("\n%c %f %d", b3.name, b3.price, b3.pages);

    printf("\n");
    return 0;
}

Can anyone please tell me why I'm not able to print name of b1 in the following program, I'm new in C, any help is appreciated.

Result

Enter the info of the books:

A 2454.45 344 
B 56566.55 355 
C 5676.66 566  

The output is:

2454.45 344 
B 56566.55 355 
C 5676.66 566`

Upvotes: 2

Views: 90

Answers (1)

Roflcopter4
Roflcopter4

Reputation: 709

Your problem is here:

struct book b1, b2, b3;
char ch;
printf("\nEnter the info of the books:\n");

while ((ch = getchar()) == '\n' && ch != EOF) { }

scanf_s("%c", &b1.name, sizeof(char));
scanf_s("%f", &b1.price, sizeof(float));
scanf_s("%d", &b1.pages, sizeof(int));

The while statement is entirely unnecessary there. stdin is empty after the printf() call, it doesn't affect that, and the while loop eats up the first character of your input. Get rid of it and the code works as expected.

It's also maybe worth noting that you might want to stick to more standard functions when you're just learning. scanf_s is a Microsoft extension.

Upvotes: 2

Related Questions