Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

Why fgets is reading the input, even though there is EOF in the input string?

I read the man page of fgets(). It states "Reading stops after an EOF or a newline". My code is as follows.

#include <stdio.h> 
#define MAX 50 
int main() 
{ 
    char buf[MAX]; 
    fgets(buf, MAX, stdin); 
    printf("string is: %s\n", buf); 

    return 0; 
} 

I gave this input :Welcome to -1 kkWorld.
Output is: string is: Welcome to -1 kkWorld
fgets should stop reading when it sees -1 in the input. Why is fgets reading even though there is -1 or EOF in the string? Am I missing something here? Please help.

Upvotes: 0

Views: 73

Answers (1)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6003

As stated by Adrian, inputing "-1" ends up being two characters; '-' and '1'. To emulate an EOF character, you must enter the single EOF value constant.

EOF can be input to the program with Ctrl-D (Unix/Linux), or CTRL-Z (Microsoft).

Upvotes: 1

Related Questions