Where does `getchar()` store the user input?
c, io, kernighan-and-ritchie, loops
Solution
It's treating the input stream like a file. It is as if you opened a file containing the text "toomanychars" and read or outputted it one character at a time.
In the first example, in the absence of a while loop, it's like you opened a file and read the first character, and then outputted it. However the second example will continue to read characters until it gets an end of file signal (`ctrl+D` in your case) just like if it were reading from a file on disk.
In reply to your updated question, what operating system are you using? I ran it on my Windows XP laptop and it worked fine. If I hit enter, it would print out what I had so far, make a new line, and then continue. (The `getchar()` function doesn't return until you press enter, which is when there is nothing in the input buffer when it's called). When I press `CTRL+Z` (EOF in Windows), the program terminates. Note that in Windows, the EOF must be on a line of its own to count as an EOF in the command prompt. I don't know if this behavior is mimicked in Linux, or whatever system you may be running.
Problem
I've started reading "The C Programming Language" (K&R) and I have a doubt about the `getchar()` function. For example this code: ``` #include <stdio.h> main() { int c; c = getchar(); putchar(c); printf("\n"); } ``` Typing `toomanychars` + CTRL+D (EOF) prints just `t`. I think that's expected since it's the first character introduced. But then this other piece of code: ``` #include <stdio.h> main() { int c; while((c = getchar()) != EOF) putchar(c); } ``` Typing `toomanychars` + CTRL+D (EOF) prints `toomanychars`. My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored? EDIT: Thanks to everyone for the answers, I start to get it now... only one catch: The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?