-5

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);`
Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43
Savn
  • 23
  • 5
  • 4
    You mean that when address of string `name` is new line or EOF, we should read the string again? – xinaiz Feb 13 '16 at 17:55
  • Do understand what `==` means in `C`? – fanton Feb 13 '16 at 18:07
  • The original program simply waits until the end of file is reached or until a newline occurs and then continues with execution. – Xaver Feb 13 '16 at 18:25
  • 1
    `name` is an array of characters or a pointer to an array of characters. `name == '\n'` is trying to compare an array (or pointer) to a constant number like the code for a line-feed or `10`. How does comparing an array to 10 make sense? – chux - Reinstate Monica Feb 13 '16 at 18:32
  • @fanton yes I know ..== this compares, = this one assigns.. – Savn Feb 14 '16 at 09:31
  • @chux just learning ! not writing operating system yet! – Savn Feb 14 '16 at 09:32

2 Answers2

1

First of, the gets function is not really secure and you might want to use fgets instead.

Anyway, your piece of code is used to clear the buffer. When you read from the user input, all the things that the user will type is going to be stored in a buffer, and then the program will read from it. That why sometimes you need to clear the buffer so you don't read other things that you didn't want.

user229044
  • 232,980
  • 40
  • 330
  • 338
haltode
  • 618
  • 6
  • 15
0

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

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67