c - I can't input when my structure has integer and character variables -
the following program written in c
#include <stdio.h> struct book { char title[80] ; char author[80]; int pages; int datepb; }; struct book input_book(void) { struct book b1; gets(b1.title); gets(b1.author); scanf("%d" , &b1.pages); scanf("%d" , &b1.datepb); return b1; } int main(int argc , char *argv[]) { struct book b1[3]; int i; (i = 0; < 3; ++i) { printf("enter book %d:\n" , + 1); b1[i] = input_book(); printf("\n"); } (i = 0; < 3; ++i) { printf("book %d:\n" , + 1); printf("%s\t%s\t%d\t%d\n" , b1[i].title , b1[i].author , b1[i].pages , b1[i].datepb); printf("\n"); } return 0; }
and output get:
enter book 1: 5 mistakes aaditua 532 enter book 2: 4 mistakes aaditya enter book 3: 9 mistakes aaditya book 1: 5 mistakes aaditua 581983988 532 book 2: 4 mistakes 1 32681 book 3: aaditya 9 mistakes 1 32681
i don't that. can input every detail of first book , while can't enter integers in second , third book. please me out appropriate answers.
you may replace;
gets(b1.title); // gets deprecated gets(b1.author);
with
fgets(b1.title,80,stdin); fgets(b1.author,80,stdin);
notice gets quite different fgets: not gets uses stdin source, not include ending newline character in resulting string , not allow specify maximum size str
then put
while(getchar()!='\n') // wasting unprocessed buffer continue;;
just after second scanf()
. below reason :
gets() can take empty strings(see citation above). if terminal line buffered, after second scanf()
, when press enter on keyboard, creates unprocessed \n
stdin
buffer , consumed next gets()
. in other words next b1.title
empty string. bad part messes whole input sequence afterwards.
reference: gets
Comments
Post a Comment