Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't getchar() recognise return as EOF on the console?

Tags:

c

I have a small snippet of code below that I'm running using PellesC.

When the code is executed and I've typed a few characters into the console, I press enter.

Can you explain to me why the printf("%ld\n", nc); line doesn't seem to get executed? As no output is written to the console.

#include <stdio.h>

int main(void)
{
    long nc = 0;

    while(getchar() != EOF)
    {
        ++nc;
    }

    printf("%ld\n", nc);
}

I've decided to learn C thoroughly using the K&R book and I'm embarrassed to say this rather elementary example has me stumped.

like image 977
Gary Willoughby Avatar asked Nov 24 '09 23:11

Gary Willoughby


1 Answers

Pressing enter doesn't actually cause an EOF ("end of file"). You have to signal that you are completely finished with providing input; on Unix you typically do that by pressing CtrlD. On Windows I believe it's CtrlZ followed by enter, but I'm really not sure about that.

like image 111
Jan Krüger Avatar answered Oct 21 '22 01:10

Jan Krüger