Confused about "while(getchar() != '\n')"

Salahuddin picture Salahuddin · Sep 13, 2011 · Viewed 9.7k times · Source

I knew that getchar() is just a function gets the first character of the line the user entered then the next and so on And if we typed getchar() in a line, at the finishing of the code,it's for let the program wait for user to type any thing and for not closing the console when displaying the info.

why we use this line of code ?

while(getchar()!='\n');

I knew that it reads all characters of the line until the end of line is found then the loop breaks .. right .? But, why this is useful ? What if we don't write this line of code ?

while((ch=fgetc(stream))!=EOF)
{
    putchar(ch);
    cha++;
    if(ch=='\n')
    {
        lines++;
        printf("Line %i is detected\n\n",lines);
        if(lines==NEW_LINE)
        {
        lines=0;
        while (getchar!='\n'); **//Here is my question**
        }
    }
}

Answer

Chowlett picture Chowlett · Sep 13, 2011

It looks like this code is paginating output.

It reads a character at a time from the stream and uses putchar to output it to stdout. Then, if that character was a newline, it increments a count of lines. If that count has hit some defined constant STOP_LINE then the count is reset and

while(getchar()!='\n');

waits for the user to press Return. The loop then continues.