LearnFrenzy
Sign in Take a free test

Error Handling · Error Handling Programs · Question 2

A robust integer parser using strtol and errno in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write parse_int() that accepts a string and a range, and reports "empty", "not a number", "trailing characters", "out of range" or the value.

Solution
main.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

const char *parse_int(const char *s, long lo, long hi, long *out) {
    if (*s == '\0')
        return "empty";
    char *end;
    errno = 0;
    long v = strtol(s, &end, 10);
    if (end == s)
        return "not a number";
    if (*end != '\0')
        return "trailing characters";
    if (errno == ERANGE || v < lo || v > hi)
        return "out of range";
    *out = v;
    return NULL;                       /* NULL means success */
}

int main(void) {
    const char *inputs[] = {"18", "", "-x", "42abc", "150", "99999999999999999999"};
    for (int i = 0; i < 6; i++) {
        long age;
        const char *err = parse_int(inputs[i], 0, 120, &age);
        printf("\"%s\": ", inputs[i]);
        if (err)
            printf("%s\n", err);
        else
            printf("age %ld\n", age);
    }
    return 0;
}

Output Verified by compiling and running

"18": age 18
"": empty
"-x": not a number
"42abc": trailing characters
"150": out of range
"99999999999999999999": out of range

Every way the input can be wrong is checked: nothing converted (end == s), extra characters (*end != '\0'), overflow (ERANGE) and the allowed range.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links