Reputation: 349
I tested this code:
1 #include <stdio.h>
2
3 main()
4 {
5 int c;
6
7 while ((c = getchar()) != EOF) {
8 putchar(c);
9 printf("%d ", c);
10 }
11 printf("%d\n", c);
12 }
Question:
When I inputted a line of characters, and then inputted an 'enter', I got this kind of result:
asdf
a97 s115 d100 f102
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
My questions are whether the 'enter' triggered the code running? Why when I input an EOF, was not the 'enter' needed to output the result? Why did I need another EOF to quit running?
Thanks a lot.
Upvotes: 2
Views: 394
Reputation: 224972
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
Upvotes: 1