-4
#include<stdio.h>
main()
{
    int c;
    c=getchar();


    while(c!=EOF)
    {
        putchar(c);
        c=getchar();
    }
}

Why this code is resulting in an infinite loop. It is from D.Ritchie's book.

Gyanshu
  • 189
  • 15

2 Answers2

2

It results in an infinite loop because EOF is not a character that can be entered via keyboard.

Take a look at this: EOF in Windows command prompt doesn't terminate input stream

Community
  • 1
  • 1
Tonci
  • 471
  • 2
  • 8
  • why ctrl-z doesn't work if not put after '\n'? I have read some explanation about this answer stating something about buffer. Please explain me what is buffer? I don't understand it at all. – Gyanshu Jan 21 '15 at 16:24
0

Execute this code in Linux after reading the last part of my answer ;)

#include <stdio.h>

int main(void)
{
    int c;
    c=getchar();

    while(c!=EOF)
    {
        putchar(c);
        c=getchar();
    }
    printf("\n %c  %d \n",c,c);

    return 0;
}

if you want to enter the EOF character you can hit Ctrl+d from the keyboard which is the end of file

you can see the last line in the output which refer to the character EOF with numeric value equals to -1

As a note EOF is a symbolic constant with value -1 and you can see its definition in the header file stdio.h

#define EOF (-1)