5

I am running this example (from Kernighan and Ritchie's C book section 1.5.2) on a mac OS X machine terminal:

#include <stdio.h>

int main()
{
    int c, nl;

    nl = 0;
    while((c = getchar()) != EOF)
        if(c == '\n')
            ++nl;

    printf("%d\n", nl);
}

I run the app and enter the EOF character CTRL-D immediately. The program outputs 0D and terminates. The 0 is the expected output, but where does the extra 'D' come from?

I saw this thread and this faq, but could not find an answer.

Community
  • 1
  • 1
Anand
  • 3,690
  • 4
  • 33
  • 64

2 Answers2

8

I bet the terminal is showing a ^D (normal caret notation) and leaving the cursor on the caret, then your program is printing 0\n because nl is 0 overwriting the caret.

Adding a sleep(5) before the final printf should confirm this.

  • 1
    On the other hand I don't know whether it's *normal* for a terminal to print the `^D` there. I don't recall seeing it on other Unices. –  Sep 10 '14 at 03:45
  • 1
    Rather than sleeping, @Anand could just start their printf format with a \n, to make sure the output starts on a fresh line. – Mark Bessey Sep 10 '14 at 03:50
0

Old post but I found the answer in another post and for any new comers googling the answer. type in the mac terminal stty -echoctl

Credit goes to Jonathan Leffler

full post and explanation on Why does C...