Compiling with Clang/GCC and running on Linux:
When running the following code I encountered what was to me unanticipated behavior: when entering a single character ("X") I will be prompted to enter another character ("Y") presumably because the buffer isn't full. When I enter a second character ("Y") putchar only displays the second character ("Y" - it neither returns the first "X" nor are there any new lines/line breaks). I presume this is because putchar is reading the stream from the end to the beginning and is reading the buffer as "[NEW LINE] Y [NEW LINE]" and that the original "X" is already beyond the buffer allocated for the three variables. But this reading from the end to the beginning of the stream doesn't seem to align with putchar's usual behaviour - if I type in four characters "XYZA" and hit enter, it returns the stream from beginning to end, understandable truncated: "XYZ".
My first question is if my presumptions above are true, my second question is: if so, why is putchar not outputting the new lines that presumably are in the buffer. If I got "[NEW LINE] Y [NEW LINE]" as output it would be clear to me what's going on, but I just get "Y". Why is that? Does putchar trim whitespace elements, or is getchar reading the new line in some way that doesn't translate into an escape-sequenced character?
I've tried a number of combinations of using the enter key but don't see how this is working. I'd like to know what it's doing.
int main() {
int a,b,c;
printf("Type three letters: ");
a = getchar();
putchar(a);
b = getchar();
putchar(b);
c = getchar();
putchar(c);
}
When running the above:
If I type three characters it returns the three characters.
If I type two characters (e.g. "XY") it returns two characters, presumably because the third character is the new line generated by hitting enter. This DOES display a new line after "XY" is displayed, which makes the following behavior that much more perplexing to me:
If I type one character, it prompts me for another character, when I type in another character it only returns the second character. Why is this? It seems to me that it's reading the buffer from the end to the beginning and trimming white-space, but this seems unlikely. I don't understand this behavior.
Even though I only get one character from the last example, which to me seems to be because putchar is reading from the end to the beginning of the stream, when typing four characters it reads as it should from beginning to end: if I type four characters it returns the first three characters in the buffer.
stdin
is usually line buffered. Nothing is given to the first getchar()
until '\n'
is entered.
Also '\n'
is one of the characters entered.