I tested this code:
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c);
printf("%d ", c);
}
printf("%d\n", c);
}
When I inputted a line of characters, and then inputted an 'enter', I got this kind of result:
asdf
a97 s115 d100 f102
But when I added an EOF(ctrl+d) directly behind a line of characters, I got the result directly behind the input, like:
asdfa97 s115 d100 f102
Does pressing 'enter' trigger the code to run? When I input an EOF, why wasn't an 'enter' needed to output the result? And why did I need another EOF to cause the program to stop?
For your first case, are you sure the output wasn't:
asdf
a97 s115 d100 f102
10
That is, your input line asdf followed on the next line by the output characters and numbers for 'a', 's', 'd', and 'f', and then another line (because you putchar() the newline character, too) with a 10 (the ASCII value for a newline character) on it?
Note that your program doesn't exit at this point either - it's still waiting for more input.
^D is not inputting an EOF "character", either. It's just sending a signal to your terminal program. In your case, it looks like it means "flush buffers", so your program gets access to the terminal's line-buffered input of "asdf". Since your program doesn't output a newline, you get the output on the same line.
If you enter the ^D on a line by itself, you'll cause the terminal to close its connection to your program and the actual EOF will come through, terminating your progam.
Example - input "asdf\n":
# ./example
asdf
a97 s115 d100 f102
10
Example - input "asdf^D":
$ ./example
asdfa97 s115 d100 f102
Example - input "asdf\n^D":
$ ./example
asdf
a97 s115 d100 f102
10 -1