简体   繁体   中英

fgets inside loop does not wait for input after encountered EOF

I use fgets inside a while loop for getting use input, if I use ctrl-d to send a EOF at the begining of line, then fgets return NULL(because it encountered EOF), and terminal print "!!!", but the problem is after that the fgets function does not wait for input, the terminal keep printing "ERROR" until loop ends. I was expecting the fgets will wait for input every loop.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{

    int argNums = 0;
    while(argNums < 20){
        char argBuf[100];
        if(fgets(argBuf, 100, stdin) != NULL){
            printf("!!!");
        }else{
            printf("ERROR ");
            //exit(1);
        }
        argNums++;
    }
    return 0;
}

This is output

1
!!!2
!!!ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR 

I want to know why this happens, thanks for helping.

Use clearerr():

The C library function void clearerr(FILE *stream) clears the end-of-file and error indicators for the given stream.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{

    int argNums = 0;
    while(argNums < 20){
        char argBuf[100];
        if(fgets(argBuf, 100, stdin) != NULL){
            printf("!!!");
        }else{
            printf("ERROR ");
            clearerr(stdin);
            //exit(1);
        }
        argNums++;
    }
    return 0;
}

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