Home > Back-end >  Why is this simple c programming reading an extra newline from stdin?
Why is this simple c programming reading an extra newline from stdin?

Time:11-28

I'm following the second edition of the K&R C book and got to exersize 1.5.1. I was playing around with their provided code and wrote the following:

#include <stdio.h>

int main() {
    int c;
    while (1) {
        printf(">>> ");
        c = getchar();
        if (c == EOF) {
            printf("\nGoodbye\n");
            return 0;
        }
        putchar(c);
        printf("\nhex: %x, dec: %d\n", c, c);
    }
}

Saved as main.c and compile with gcc main.c -o main. Here's an example output when I successively input 1, 12, then ^D:

./main
>>> 1
1
hex: 31, dec: 49
>>> 

hex: a, dec: 10
>>> 12
1
hex: 31, dec: 49
>>> 2
hex: 32, dec: 50
>>> 

hex: a, dec: 10
>>> 
Goodbye

Notice the empty >>> lines. These indicate to me that getchar is picking up on the linefeeds I provide when I press the enter key. However, if I simply remove the last printf (line 13), recompile, and rerun with the same input, this is the output I get:

./main
>>> 1
1>>> 
>>> 12
1>>> 2>>> 
>>> 
Goodbye

As you can see, the code is no longer acting as though it received empty linefeeds as input. Why does removing the last printf cause this?

CodePudding user response:

Upon further inspection, the program is acting as it should be. Thank you @KamilCuk, I'm not entirely sure how I missed that.

CodePudding user response:

./main
>>> 
1>>>                << empty line
>>> 12
1>>> 2>>>           << empty line
>>> 
Goodbye
  • Related