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.
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.