While loop asking for input until ctrl-d using C

前端 未结 2 1451
借酒劲吻你
借酒劲吻你 2021-01-28 15:37

I want to make a while loop that is continually asking a user for input until the user ctrl-d\'s out of it. How can I do this correctly? I am using this ri

相关标签:
2条回答
  • 2021-01-28 15:53

    You have to test for EOF, which is what CTRL-D returns.

    So do this:

    while ( fgets( ... ) != NULL ) {
        ...
    }
    

    EDIT:

    Since you're prompting, even better would be:

    for ( ;; ) {
        printf( "enter input: " );
        fflush( NULL );   // make sure prompt is actually displayed, credit Basile Starynkevitch
        if ( fgets( input, ... ) == NULL ) break;
    
        // handle input here
    }
    
    0 讨论(0)
  • 2021-01-28 15:53

    A ctrl-d will send an EOF (end of file) character, which translates in fgets as a NULL pointer :

    while (fgets(user_input, 1000, stdin) != NULL) {
        // do stuff...
    }
    // no more user input
    
    0 讨论(0)
提交回复
热议问题