1

i am working on a database basic project consider a structure

struct student
{ 
int rollno;
char full_name[20];
char address[50];
char birthmark[50];
};

how to take this input

rollno 6

name john snow

address winterfell of north

birthmark swords wound all over

What I have tried:

i have tried

scanf("%s",stringname),scanf("%[^\n]s",stringname),gets(stringname), fgets(buffer,size,stdin) with fflush(stdin). there are always some error. so far fgets work perfectly but I have read ffush(stdin) is a wrong practice .

so what should be the approach to take input of string (with spaces) simultaneously one after the another.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
ekaf
  • 153
  • 2
  • 13

1 Answers1

2

The best approach will be , reading a whole line from input by fgets() and then parse and validate before you populate the members of the structure. A flow chart can look like

fgets(into the buffer) and the return is not NULL
if (integer)
store into rollno;
else 
copy the input string into corresponding member variable.

And yes, fflush(stdin) invokes undefined behavior, don't use that.


(Without the code with error and mcve, that's all the help we can do)

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • thanks but there are some error when fgets is followed by scanf(),in that case what to do . for example scanf("%s",var);fgets(par1,par2,par3); in this case fgets eat the new line left by scanf .should i flush that ? – ekaf Jul 13 '16 at 10:55
  • 2
    @ekaf why don't you use `fgets()` all the time? (_Sorry, personally I'm not a fan of `scanf()` family_) – Sourav Ghosh Jul 13 '16 at 10:56
  • 2
    okay from now on words only fgets while dealing with string :) thanks for the help – ekaf Jul 13 '16 at 10:58
  • 1
    If all learners started with `fgets()` and not "learned" with `scanf()`, think of all the fewer SO posts there would be. @ekaf Also review http://stackoverflow.com/q/2693776/2410359 – chux - Reinstate Monica Jul 13 '16 at 13:18