Reputation: 315
In this code:
#include<stdio.h>
int main()
{
int i,p=0;
while(i!=EOF)
{
i=getchar();
putchar(i);
printf("\n");
}
return 0;
}
When I enter hello as input in one go, the output is h then in the next line e and so on. But when h is printed then before printing e why getchar()
doesn't take pause to take input from me just like it did in the first time?
getchar()
returns either any successfully read character from stdin or some error, so which function is demanding terminal input and then sending it to stdin?
Upvotes: 0
Views: 62
Reputation: 224546
Input from a terminal is generally buffered. This means it is held in memory waiting for your program to read it.
This buffer is performed by multiple pieces of software. The software that is actually reading your input in the terminal window generally accumulates characters you type until you press enter or press certain other keys or combinations that end the current input. Then the line that has been read is made available to your program.
Inside your program, the C standard library, of which getchar
is a part, reads the data that has been sent to it and holds it in a buffer of its own. The getchar
routine reads the next character from this buffer. (If the buffer is empty when getchar
wants another character, getchar
will block, waiting for new data to arrive from the terminal software.)
Upvotes: 1
Reputation: 11
It's because of the loop condition. You are continuing to loop until EOF is received. When you type "hello", it works exactly as you expect except STDIN has more characters in the buffer and none of them are EOF. The program prints out "h", then a newline, and goes back to check the loop condition. EOF has not been found, so then it gets the next character from STDIN (which you have already provided) and the cycle repeats.
If you remove the loop it will only print one character.
Upvotes: 1