In c what does this do after gets
int c;
while ((c = getchar()) != EOF && c != '\n');
I saw that many of you are telling me its while loop and all, why so much complication to it? Why cant we just use this code which I have given below?
gets(name);
if(name == '\n'|| name == EOF)
gets(name);`
Well, this piece of code
int c;
while ((c = getchar()) != EOF && c != '\n');
is used to clear the buffer, as mentioned in @napnac's answer. It is mainly used instead of fflush (stdin);
, which is UB. But note that this is successful only if the input buffer happens to contain data ending in a newline.
Otherwise, you can use fflush (stdin);
, which is not recommended. You can also use the flushinp
function provided by the curses library. It throws away any typeahead that has been typed by the user and has not yet been read by the program