C: ¿Cómo simular un EOF?


Actualmente estoy leyendo el libro de K & R y escribiendo los ejemplos de la primera sección, y hay un par de ejemplos como este:

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

Estoy probando estos ejemplos en un cuadro de Windows y, por lo tanto, ejecutando los archivos exe compilados desde el símbolo del sistema cmd.

Para probar el ejemplo anterior, ¿cómo simulo un EOF? Es decir, básicamente, ¿cómo puedo hacer que el bucle se detenga al probar el ejemplo desde el símbolo del sistema?

Author: artm, 2009-07-13

4 answers

Para introducir un EOF, utilice:

  1. ^Z (CtrlZ) en Windows
  2. ^D en sistemas Unix-like
 80
Author: Greg Hewgill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-14 07:42:29

Refiérase EOF

Windows: Ctrl+Z
Unix :Ctrl+D
 21
Author: aJ.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-13 11:35:44

Primero, presione: Ctrl^X, siguiente: Ctrl^D

 2
Author: user3078185,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-07 18:10:36

También puede simular EOF dando explícitamente a la variable int un valor de -1.

Echa un vistazo a este código para más claridad:

#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;
}
 1
Author: Shivam Agarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-22 16:56:39