Barath Ravikumar
Barath Ravikumar

Reputation: 5836

Behavior of getchar() inside while loop

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 ?

Upvotes: 3

Views: 515

Answers (3)

Rerito
Rerito

Reputation: 6086

I will omit I/O mechanisms of the system to supply the input stream to your program and getting the output stream from it. (Since I don't know them)

The getchar() function simply retrieves one character from stdin. On the other way, putchar() just puts one character to the output stream (stdout). Thus, there is no buffer magic involved here, you're just getting what you would expect to get : a perfect copy of what has been put in stdin in stdout.

Upvotes: 0

Ferruccio
Ferruccio

Reputation: 100638

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.

Upvotes: 2

James
James

Reputation: 25513

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

Upvotes: 2

Related Questions