The scanf() is certainly a function that has many problems, so I've been looking for a way to substitute it.
I found this code in the first answer of this post, but even this code is bugged (the loop end if the user enter a newline).
There's a way to get an integer in input without encountering any types of bug?
Code:
char *end;
char buf[LINE_MAX];
do {
if (!fgets(buf, sizeof buf, stdin))
break;
// remove \n
buf[strlen(buf) - 1] = 0;
int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));
EDIT:
I wrote this function based on the answer of @chqrlie and on a snippet of code that I found [here][2], is there any way to improve the function and make it better?int readInteger(const char *prompt, const char *error) {
int number;
char buf[1024]; // use 1KiB to be sure
while(1) {
printf("%s", prompt);
if(!fgets(buf, 1024, stdin)) exit(1); // reading input failed
// have some input, convert it to integer
char *endptr;
errno = 0;
number = (int)strtol(buf, &endptr, 10);
while(isspace((unsigned char)*endptr)) endptr++; // ignore trailing white space
if(errno == ERANGE) printf("%s", error);
else if(endptr != buf && !(*endptr && *endptr != '\n')) return number;
}
}