Reputation: 189
Definition: A text stream is a sequence of characters divided into lines; each line consists of zero or more characters followed by a newline character. This definition is verbatim from K&R.
I am reading K&R The C Programming Language, and I am a little confused by how the input and output is occuring. So I wrote a little program to see how it works, this is what I get:
The while
loop gets a character and saves it as char c
then it executes
putchar(c)
and so on until I hit return (ending the text stream), the part that confuses me is: as I type the input text stream putchar(c)
doesn't appear to be working (it is certainty not printing c
with each iteration of the loop), but as soon as I hit return I get back what I typed.
I think the following is happening, but I hope someone can confirm or correct it. as soon as I execute inputOutput.exe
in the first line of the Command Prompt it is set to receive an input text stream (this is not a result of the program, but of how the command prompt works.) As I type text into the Command Prompt each character is being sent to an "output text stream" by putchar(c)
, but that stream is not visible from the Command Prompt until after i hit return on my keyboard, at which time the Command Prompt ends the input mode, it then executes the last putchar(c)
which invokes the current output text stream to be presented on the Command Prompt. If this is correct then, it seems to me the way in which the code manifest itself is governed by the rules of the command prompt and not so much by the C language, is this correct?
Upvotes: 1
Views: 978
Reputation: 1232
The reason putchar(c) doesn't immediately show the character on screen is buffering. You could add:
fflush(stdout);
right after
putchar(c);
and output will make more sense.
You can also turn off buffering, but usually you want it on.
The reason you want buffering, is if you're writing out a lot of data, it will be a lot faster for C-runtime to buffer the text and flush it out all at once (or a buffer at a time).
It is normal for UI-type programs in C, to do:
printf(... printing things);
printf(... printing some more things);
...
fflush(stdout); /* at this point everything will be seen by user */
Upvotes: 2
Reputation: 45664
That is an artifact of line-buffering on input. Many Consoles/Programs do that, sometimes even allowing advanced input editing. Try putting your console/program in direct mode / unbuffered.
Upvotes: 3