0

I'm trying to work through "The C Programming Language", and I'm running into some issues with printf and the EOF character. I'm working the the mac terminal and compiling with clang.

Running this code:

#include <stdio.h>

main()
{
    int val;
    while ((val = getchar()) != EOF)
        printf("%d\n", val);
    /*val = 5;*/
    /*printf("hi\n");*/
    /*printf("%d\n", val);*/
    printf("%d\n", val);
}

works like I would expect, blocking till I enter a character then printing: "*character code*\n10\n", except for ctrl-d, which prints "-1" then exits.

After uncommenting the "val = 5;" statement however, entering "ctrl-d" causes it to print: "5D".

I messed around with it and found that printing val a second time (the third commented statement) will result in only one "D": "5D\n5", and that printing a constant before the variables (the second commented statement) stops the "D" from appearing: "hi\n5\n5".

I absolutely do not want the D and if anyone could explain how to remove it, I would be very grateful.

scalauser
  • 1,327
  • 1
  • 12
  • 34

1 Answers1

2

So, what happens is the console input is printing what you type. Just like if you type the letter A, the letter A gets printed. The CTRL-D gets printed to the stdout as ^D.

If you print out 1 character, the ^ is overwritten. If you print out 2 characters, both the ^ and D are overwritten. So, -1 overwrites it, hi overwrites it, but 1 character will not.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23
  • This is 'normal' on Mac; I'm not so sure about other systems, though I'm sure you can get it to happen on Linux too. The `stty` setting `echoctl` controls this, I believe (check with `stty -a`). – Jonathan Leffler Jun 02 '15 at 06:48
  • Actually, Linux (Ubuntu 14.04) does not echo `^D` when that is the EOF. It will echo `^A`, `^B`, etc for a number of other characters — but beware of those which have a special meaning. Mac does echo `^D` too. – Jonathan Leffler Jun 02 '15 at 07:05