2

i am learning The C Programming Language" by Kernighan and Ritchie (2nd edition), Exercise 1.06 on page 17

my question is why everytime i enter ctrl-d, it prints "0D", not "0", my computer is iMAC m1 chip. thanks

#include <stdio.h>

main()
{
    printf("%d\n", getchar() != EOF);
}
JackSea
  • 21
  • 3
  • Might be a duplicate: https://stackoverflow.com/questions/21364313/signal-eof-in-mac-osx-terminal. But I wouldn't know, since I would never even consider a mac for (the purpose of learning) programming... – Lundin Aug 23 '23 at 06:54

1 Answers1

4

The reason for your observations is when you type Ctrl-D the terminal echoes ^D and 2 backspaces (BS) and returns 4 immediately. The effect is the cursor is on the ^ character on the screen and when printf outputs 0 and a newline, the 0 overwrites the ^ and the newline is converted to a CR+LF, causing the cursor to go to the beginning of the next line.

You can modify your program to avoid this problem by printing a newline before the %d conversion:

#include <stdio.h>

int main(void) {
    printf("\n%d\n", getchar() != EOF);
    return 0;
}

Output:

^D
0
chqrlie
  • 131,814
  • 10
  • 121
  • 189