Search code examples
cscanfstdin

Proper way to read integer with scanf?


I would like to implement a function that read an integer but this function should be:

  • Resilient to \n
  • Robust against ^D (EOF)
  • Compliant with printf "42 20 10" | ./a.out

For now I wrote this but I feel it is ugly and too complicated:

#include <stdio.h>
#include <stdbool.h>

int read_integer(char *text, int min, int max, int nom) {
    int n;
    bool failure = false;

    do {
        printf("%s [%d] ? : ", text, nom);

        // Slurp spaces    
        scanf("%*[\t ]");

        // Hack to capture default value
        char buf[2];
        if (scanf("%1[\n]", buf) == 1) {
            return nom;
        }

        if (failure = (scanf("%d", &n) == 0 || n < min || n > max)) {
            if (feof(stdin)) {
                printf("\n");
                return nom;
            }
            printf("Error: value should be between %d and %d!\n\n", min, max);
            scanf("%*[^\n]%*1[\n]");
        }     

    } while(failure);

    scanf("%*[^\n]%*1[\n]");

    return n;
}

int main(void) {
    do {
        printf("You said %d\n", read_integer("What's the answer", 10, 50, 42));        
    } while(!feof(stdin));
}

Is there a better way?

Currently it does not work, the line before the end captured 42 which was never entered, and a new line is not displayed:

$ gcc main.c && ./a.out
What's the answer [42] ? : oops
Error: value should be between 10 and 50!

What's the answer [42] ? : 100
Error: value should be between 10 and 50!

What's the answer [42] ? : You said 42
What's the answer [42] ? :

EDIT

From the comments, I tried to write the same using fgets, but still it is not perfect. Or at least very complicated...

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

/**
 * Read an integer from `stdin`.
 * @param min Minimum accepted value
 * @param max Maximum accepted value
 * @param nom Default value
 * @return captured integer
 */
int read_integer(char *text, int min, int max, int nom) {
    int n = nom;
    bool failure = false;

    do {
        printf("%s [%d] ? : ", text, nom);

        // Read user input
        char line[24];
        do {
            if (fgets(line, sizeof(line), stdin) != line || feof(stdin)) {
                exit(EXIT_FAILURE);
                break;
            }
        } while (strchr(line, '\n') == NULL);

        // Default value?
        {
            char *cursor = line;
            while ((*cursor == ' ' || *cursor == '\t') && *cursor != '\0') {
                cursor++;
            }        
            if (*cursor == '\n') {
                return n;
            }
        }

        // Not a number ?
        if (sscanf(line, "%d", &n) != 1) {
            printf("Error: this is not valid entry!\n\n");
            continue;
        } 

        // Not in the range ?
        if (n < min || n > max) {
            printf("Error: value should be between %d and %d!\n\n", min, max);
            continue;
        }

        return n;
    } while(true);
}

int main() {
    do {
        printf("You said %d\n", 
            read_integer("What's the answer", 10, 50, 42));        
    } while(!feof(stdin));
}

Solution

  • Use fgets and strtol, and don't forget to complain if strtol ignores extra characters (use the optional endptr to check it). Put the fgets and strtol into a function, and add your validation around the call to that function, so you don't repeat the same code every time you read an integer.