Search code examples
cwhile-loopcharscanfgetchar

C program on Mac works unexpected


I have this little program:

#include <stdio.h>

int main(){
    int c;
    while(c != EOF){
        printf("Enter character\n");
        c = getchar();
        printf("Character: %c\n", c);
    }
    printf("FIN\n");
    return 0;
}

The output of the terminal seems odd, because the while loop gets executed twice after a character was entered:

Enter character
a
Character: a                //This should be the last output after a char was entered, but the loop gets executed a second time without waiting for a keyboard-input:
Enter character
Character: 

Enter character

 

In the terminal I'm compiling and running the code like this:

gcc main.c
./a.out

What am I doing wrong?

Thanks for the answers, It's the lf entered by enter .... It's so obvious :D


Solution

  • You are entering 2 characters, the 'a' and a LF.

    The while test is not made until both have been processed.