EOF reading C/C++

柔情痞子 提交于 2019-12-31 04:50:08

问题


I'm using NetBeans MinGW to compile simple c programs(I'm new at this). My problem is that I have this simple code

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    int c,i=0;
    while((c=getchar())!=EOF){
        i++;
    }
    printf("%d",i);
    return 0;
}

and when I try to end input like this:

hello^Z [enter]

it doesn't do it, I need to re-enter

^Z[enter]

to end it.

I'd appreciate that you tell me why this happens.

Thanks in advance


回答1:


C input is line-oriented by default. Ending a line with the EOF character (^Z on Windows, ^D on Unix) ends the line (without a trailing newline) but doesn't actually signal end of file; the end of file condition is signaled when it's encountered on the next read, i.e. at the beginning of a line.




回答2:


Just the way the console handles input

Ctrl-Z on a UNIX system would be an interrupt to let you suspend the process, so I guess it is a Windows console.

When you Ctrl-Z after the characters it probably does treat this as an "End" which is Ctrl-Z on its own.



来源:https://stackoverflow.com/questions/5406588/eof-reading-c-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!