Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of getchar() inside while loop

Tags:

c

int main()
{
int c;

  while ( (c = getchar())  != EOF)
    putchar(c);

}

Now ,running the above program produces

$./a.out thisisthelinewhosestoragelocationisamysterytome -- LINE1 thisisthelinewhosestoragelocationisamysterytome -- LINE2

When i entered the characters of LINE1 , i think the functions getchar() and putchar() , have been processing the characters , or am i wrong ?

Here is my question.

After i hit enter , my LINE1 is duplicated exactly to LINE2 , which means it should have been buffered elsewhere , so where is it stored ? Also why is it implemented this way ?

like image 860
Barath Ravikumar Avatar asked Dec 07 '25 19:12

Barath Ravikumar


2 Answers

Your program doesn't receive input from the shell until you've entered a whole line.

like image 70
James Avatar answered Dec 09 '25 16:12

James


The default behavior of the system is to buffer the input until it sees a newline so that you have the option of hitting backspace and making edits to the line before your program sees it.

like image 44
Ferruccio Avatar answered Dec 09 '25 15:12

Ferruccio