Why doesn't getchar() recognise return as EOF

2019-01-01 16:19发布

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.

标签: c
8条回答
何处买醉
2楼-- · 2019-01-01 16:52

ENTER is written in code as '\n'. Try this

#include <stdio.h>

int main(void)
{
    long nc = 0;

    /* count chars, except for ENTER */
    while(getchar() != '\n')
    {
        ++nc;
    }

    printf("%ld\n", nc);
    return 0;
}
查看更多
大哥的爱人
3楼-- · 2019-01-01 16:58

"Press enter"? The cycle in your code continues to iterate until it reaches the end-of-file marker. "Pressing enter" will not result in EOF. If you want to simulate EOF from the keyboard, consult the documentation for your terminal. In Windows, for example, you'd have to hit Ctrl+Z to generate EOF.

查看更多
登录 后发表回答