cgccclanggetcharputchar

Why is putchar not returning a new line when entered with getchar?


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:


Solution

  • stdin is usually line buffered. Nothing is given to the first getchar() until '\n' is entered.

    Also '\n' is one of the characters entered.