I wanted to write a C function C99/POSIX compliant that read an integer from the user input. I wanted this function to be safe and robust but I feel it is way too complex for such simple task.
I am wondering whether this code is optimal.
#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));
}