atoi in C: solved exercise

atoi in C: solved exercise

If you searched for a solved atoi exercise in C, here are the key patterns: converting strings to integers with atoi, understanding its limitations (no error handling), and the recommended alternative with strtol that can detect invalid input.

atoi (ASCII to integer) is the simplest conversion function, but it returns 0 for both "0" and invalid input like "abc", making it unsuitable when you need to distinguish an error from a legitimate zero value.

Problem statement

  1. Convert the strings "42", "-17", " 100 ", and "3abc" with atoi and print the results.
  2. Repeat the conversions with strtol, detecting format errors and overflow.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

void convert_strtol(const char *s) {
    char *end;
    errno = 0;
    long val = strtol(s, &end, 10);

    if (end == s) {
        printf("  strtol(\"%s\"): ERROR - no digits\n", s);
    } else if (errno != 0) {
        printf("  strtol(\"%s\"): ERROR - overflow\n", s);
    } else if (*end != '\0') {
        printf("  strtol(\"%s\"): %ld  (trailing: \"%s\")\n", s, val, end);
    } else {
        printf("  strtol(\"%s\"): %ld  OK\n", s, val);
    }
}

int main(void) {
    /* 1. atoi */
    const char *cases[] = {"42", "-17", "  100  ", "3abc", "abc", NULL};
    printf("atoi:\n");
    for (int i = 0; cases[i]; i++)
        printf("  atoi(\"%s\") = %d\n", cases[i], atoi(cases[i]));

    /* 2. strtol with error detection */
    printf("\nstrtol:\n");
    const char *cases2[] = {"42", "-17", "3abc", "abc", "99999999999", NULL};
    for (int i = 0; cases2[i]; i++)
        convert_strtol(cases2[i]);

    return 0;
}

Expected output

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
atoi:
  atoi("42") = 42
  atoi("-17") = -17
  atoi("  100  ") = 100
  atoi("3abc") = 3
  atoi("abc") = 0

strtol:
  strtol("42"): 42  OK
  strtol("-17"): -17  OK
  strtol("3abc"): 3  (trailing: "abc")
  strtol("abc"): ERROR - no digits
  strtol("99999999999"): ERROR - overflow

Common mistakes

  • Using atoi to validate user input: it returns 0 for both "abc" and "0", with no way to distinguish between the two.
  • Not setting errno = 0 before strtol: errno may contain a value from a previous operation, causing false positive errors.
  • Not checking that end != s: if end == s, no digits were consumed — the string did not contain a number.
  • Confusing strtol’s third parameter (the base) with a length: strtol(s, &end, 10) uses base 10; passing 0 auto-detects 0x (hex) and leading 0 (octal).

Practical use

String-to-integer conversion appears in command-line argument parsing, configuration file reading, and network data deserialization. strtol is the industry standard for this purpose in C.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

When is it fine to use atoi and when is strtol necessary?

atoi is acceptable in quick code where you know for certain the input is a valid integer (for example, after validating with isdigit). Use strtol when input comes from the user, a file, or the network and you need to distinguish errors from legitimate values.

How does strtol convert in other bases?

The third parameter is the base: strtol(s, &end, 16) converts hexadecimal, strtol(s, &end, 2) binary. With 0 it auto-detects the prefix: 0x for hex, a leading 0 for octal, and no prefix for decimal.

Is there an equivalent for double?

Yes: strtod(s, &end) converts a string to double using the same error-detection mechanism via the end pointer.