cinputstdinfgetsgoto

Is there an better/efficient way to keep asking for user input from STDIN using fgets() in C?


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

#define MAXSIZE 10

int main(int argc, char *argv[]){
    char input[MAXSIZE], c, *input_ptr;
    input_tag: printf("Enter the initial data string : ");
    input_ptr = fgets(input, MAXSIZE, stdin);                    //get input
    if(input_ptr != NULL && strcspn(input,"\n") == MAXSIZE-1){   //check if input fits in buffer
        printf("Buffer overflow. Reduce size of input.\n");
        while((c = getchar()) != '\n')                           //loop through rest of STDIN to discard extra characters until newline
        goto input_tag;                                          //Request for user input again
    }
    input[strcspn(input,"\n")] = '\0';                           //Remove newline character
    printf("Input is %s\n", input);
    return 0;
}

Is it possible to keep requesting the user for new input without using the goto statement? Is there a better way to do what I have done? Because, I keep reading that using goto statement should be avoided if possible.


Solution

  • A do/while loop can be used to avoid goto.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXSIZE 10
    
    int main ( void){
        char input[MAXSIZE] = "";
        int c = 0;
        size_t count = 0;
    
        do {
            printf("Enter the initial data string : ");
            if ( NULL == fgets(input, MAXSIZE, stdin)) {
                fprintf ( stderr, "problem fgets returned NULL\n");
                return 1;
            }
            count = strcspn ( input, "\n"); // count to newline or terminating zero
            // printf ( "count %zu\n", count);
            if ( input[count] != '\n') { // did not count to newline
                while ( ( c = getchar ( )) != '\n') {
                    if ( EOF == c) {
                        if ( 0 != count) {
                            break;
                        }
                        fprintf ( stderr, "found EOF\n");
                        return 1;
                    }
                }
                if ( EOF != c) {
                    printf ( "\nBuffer overflow. Reduce size of input.\n");
                }
            }
        } while ( input[count] != '\n' && EOF != c);
    
        input[count] = '\0'; //Remove newline character
        printf ( "Input is %s\n", input);
        return 0;
    }