开发者

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

开发者 https://www.devze.com 2023-04-04 09:20 出处:网络
I knew that getchar() is just a function gets the first character of the line the user entered then the next and so on

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**
        }
    }
}


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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号