Multiple word input in string in c -
while writing c program wrote following code can put more 1 word each string '
#include<stdio.h> struct address { char house[20],street[20],city[10]; }; struct student { struct address a; }; struct student getdata(); struct student getdata() { struct student s; printf("\n\nenter data\n\n"); printf("house : "); if(fgets(s.a.house,20,stdin)); printf("street : "); if(fgets(s.a.street,20,stdin)); printf("city : "); if(fgets(s.a.city,10,stdin)); return s; } int main() { struct student s; int i; printf("\nenter number\n"); scanf("%d",&i); s=getdata(); }
but in terminal got
house : street :
that unable feed data house instead takes me directly towards street.
after calling scanf
, there newline left in input buffer. when fgets
later called, reads buffered newline , returns immediately.
to clear input buffer after scanf
, call getchar
read characters until read newline.
scanf("%d",&i); while (getchar() != '\n'); s=getdata();
Comments
Post a Comment