-2
while((c= getchar()) != '\n' && c != EOF);

I was facing a problem by using gets() to enter strings. I found on google that it was keeping the value of '\n' in the input buffer. I searched here and found the above code to solve my problem. However I don't quite get the hold of it. What does this do ?? Anybody please enlighten me.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Adi
  • 89
  • 1
  • 1
  • 13

2 Answers2

4

An assignment in C++ will also yield the value being assigned. So c= getchar() is reading the next character from the file, and (c= getchar()) != '\n' is comparing that read character to the newline character. There's another test for the special EOF value, to make sure it doesn't keep trying to read once you reach the end of the file.

There's no statement between the while and the closing semicolon because nothing else needs to be done, you're throwing the input away.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • So basically what it does is that after I input the string, it reads the string until it finds a new line character and EOF ie -1 ?? – Adi Oct 04 '14 at 12:42
  • 3
    @gotolabeladi Until it finds a new line character ***or*** EOF. – Boann Oct 04 '14 at 14:13
2

The code introduces a while-loop. Its exit condition assigns the integer c the value that getchar() returns, and checks whether it is equal to the newline character ('\n') or EOF. If it is, the loop exits. If it isn't, the next character is extracted, and so on.

The code basically skips all characters until the next newline or EOF is reached. It is equivalent to:

for (;;)
{
    c = getchar(); // c has been declared elsewhere
    if (c == '\n' || c == EOF)
        break;
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Columbo
  • 60,038
  • 8
  • 155
  • 203