OSX 10.6.8, GCC 4.2 86_64
#include <stdio.h>
/* count lines in input */
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
Run
./a.out
press ctrl+d to send EOF
0D
It should be just 0. Why does it append D? What does it mean?
I’ve seen this one – it confused me, too.
The terminal is echoing
^Dand then the0is output from the program, overwriting the caret.You can demonstrate this by changing the print format in your program to
"\n%d\n".When asked ‘Why?’, I went exploring. The answer is in the tty settings. For my terminal, the output from
stty -ais:Notice the
echoctlat the end of the second line – it is for ‘echo control characters’.You can’t see it, but for each
catcommand, I typed a Control-D at the end of the line ofasdcharacters, and a second one after hitting return. The prompt erased the second echoed^Din the second example.So, if you don’t like the control characters being echoed, turn the echoing off:
The shell can also get in the way; I experimented with Control-R and my shell (
bash) decided to go intoI’d typed the unoriginal sequence of ‘asd’ characters and then typed Control-R, and this is where I ended up in the shell. I interrupted; I’m not sure what a reverse-i-search is, but I suspect it is Emacs-ish; it was not what I expected.