1

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**
        }
    }
}
haccks
  • 104,019
  • 25
  • 176
  • 264
Salahuddin
  • 1,617
  • 3
  • 23
  • 37

2 Answers2

2

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.

Chowlett
  • 45,935
  • 20
  • 116
  • 150
  • in fact if there isn't that line of code -while(getchar()!='\n'); it doesn't differ at all , the program also waits for anything else , it doesn't close -when running on terminal or the GUI console in the eclipse compiler itself- please explain why – Salahuddin Sep 13 '11 at 19:00
  • Without seeing the rest of the code, or knowing what `stream` is, we can't really tell. Perhaps `stream` only has less than `STOP_LINE` lines; or never produces an `EOF`, so the outer loop never exits? – Chowlett Sep 13 '11 at 19:34
0
while(getchar()!='\n');

Reads all characters of the line until the end of line is found.

There would be more efficient ways to do this, however (like using a buffered stream, or reading larger chunks if possible)

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • 6
    And it's not very safe. It `EOF` (or an error) is encountered, this will go in an infinite loop. – Mat Sep 13 '11 at 15:35
  • but i see it alot in different codes in the book i'm studying so arnaud what after the end of line is found ?? what is the actual function . and how to use this more efficient ways ? – Salahuddin Sep 13 '11 at 19:02