简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM