59

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?

pppery
  • 3,731
  • 22
  • 33
  • 46
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360

5 Answers5

102

To enter an EOF, use:

  1. ^Z (CtrlZ) in Windows
  2. ^D on Unix-like systems
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
21

Refer EOF

Windows: Ctrl+Z
Unix :Ctrl+D
aJ.
  • 34,624
  • 22
  • 86
  • 128
2

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

1

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;
}
sschrass
  • 7,014
  • 6
  • 43
  • 62
1

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.

Arun AK
  • 4,353
  • 2
  • 23
  • 46
Toffy_
  • 11
  • 4