why my " scanf " function do not work in structure data type | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

why my " scanf " function do not work in structure data type

my scanf function is : scanf("%c %f %d",&b1.name, &b1.price, &b1.pages); scanf("%c %f %d",&b2.name,&b2.price,&b2.pages); my code give me a garbage value.

2nd Jun 2020, 4:17 AM
kiran upase
kiran upase - avatar
4 Answers
+ 4
When you enter the 3 values for the first scanf() and hit enter, the newline will be read by the second scanf() which skips the assignments to b2 and the values meant for b2 are instead assigned to b3, leaving b2 uninitialized. You can fix it by adding a space at the beginning: scanf(" %c %f %d", &b2.name, &b2.price, &b2.pages); And if you want name to be more than one character, then do what lpang said.
2nd Jun 2020, 6:57 AM
Gen2oo
Gen2oo - avatar
+ 2
Share the link to your full code here so people can check it for problem. Follow this guide if yiu didn't know how to share the code link 👇 https://www.sololearn.com/post/75089/?ref=app
2nd Jun 2020, 4:28 AM
Ipang
+ 2
Book name should be array of `char`. You can only read one character/letter with just `char`, I suppose book title should be more than just a one character. I'll look further later on ...
2nd Jun 2020, 4:41 AM
Ipang
+ 1
This is my full code : #include<stdio.h> #include<stdlib.h> struct book { char name; float price; int pages; }; void main(){ struct book b1, b2, b3; printf("\nEnter neme , prices & pages of 3 books \n"); scanf("%c %f %d",&b1.name, &b1.price, &b1.pages); scanf("%c %f %d",&b2.name, &b2.price, &b2.pages); scanf("%c %f %d",&b3.name, &b3.price, &b3.pages); printf("\nAnd this is what you entered\n"); printf("%c %f %d\n",b1.name, b1.price, b1.pages); printf("%c %f %d\n",b2.name, b2.price, b2.pages); printf("%c %f %d\n",b3.name, b3.price, b3.pages); }
2nd Jun 2020, 4:32 AM
kiran upase
kiran upase - avatar