C : How to simulate an EOF?

元气小坏坏 提交于 2019-12-17 01:02:54

问题


I am currently reading K&R's book and typing in the examples from the first section, and there are a couple of examples such as this:

while((c = getchar()) != EOF) {
    //do something
}

I am testing these examples on a Windows box and thus running the compiled exe files from the cmd prompt.

To test the example above, how do I simulate an EOF? That is, basically how can I make the loop stop when testing the example from the command prompt?


回答1:


To enter an EOF, use:

  1. ^Z (CtrlZ) in Windows
  2. ^D on Unix-like systems



回答2:


Refer EOF

Windows: Ctrl+Z
Unix :Ctrl+D



回答3:


First, press: Ctrl^X, next: Ctrl^D




回答4:


You can also simulate EOF by explicitly giving int variable a value of -1.

Check out this code for more clarity:

#include<stdio.h>

int main() {    
    // char ch=getchar()
    // int ch=-1;

    if(ch==EOF) { printf("\nEOF: %d",EOF); }
    if((ch!=EOF)==0) { printf("\nit is equal to 0"); }
    if((ch!=EOF)==1) { printf("\nit is equal to 1"); }
    else { printf("\n it is equal to other value"); }
    system("pause");
    return 0;
}



回答5:


I had the same problem after pressing Ctrl+d program stopped and returned 0. If you use Clion press Ctrl+Shift+a than type Registry press enter and make sure run.processes.with.pty. is unchecked. After that compile program again and then you can type in input but don't press Ctrl+d on the same line as input it will return 0 or Error.



来源:https://stackoverflow.com/questions/1118957/c-how-to-simulate-an-eof

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