1
int main()
{
    int c;
    c = getchar();
    while (c!=EOF){
        putchar(c);
        c=getchar();
    }
    return 0;
}

in above code when I input value -1 why the loop doesn`t get terminated.
value of EOF = -1 I got from this code,

main()
{
    printf("EOF is %d\n",EOF);
}

code get terminated when I use Ctrl+D,is there any other way to terminate the same code without using Ctrl+D.

Himanshu
  • 4,327
  • 16
  • 31
  • 39
Hitesh
  • 33
  • 5

2 Answers2

8

Because typing -1 on console doesn't generate EOF. Instead getchar() reads it as two separate characters '-' and '1'.

If you want to terminate it with -1 input then you have to keep track of two characters and compare them to exit the loop instead of comparing against EOF. But that is really not equivalent of generating an EOF.

Another option to terminate is to redirect standard input to a file via input redirection < in console. When the reading from input file ends it will signal an EOF.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
1

If you want to loop out of the code without pressing ctrl+D then there are multiple ways of doing it. I will show you the easiest and inefficient way of doing it using a basic if condition. Go through the code and if you have any doubt please feel free to comment on it.

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

int main()
{
int c;
c = getchar();
while ((c != EOF))
{
    if (c == 'i')
        break;
    putchar(c);
    c = getchar();

}
return 0;
}
taskinoor
  • 45,586
  • 12
  • 116
  • 142
Vimal Bhaskar
  • 748
  • 1
  • 5
  • 17