Convert a string to an integer in C

This example program demonstrates how to convert a string to an integer in C using atoi and strtol.

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

static void
run_strtol (const char * input)
{
    int output;
    char * end;

    printf ("With strtol, %s", input);


    /* The 10 at the end means to use base 10. */

    output = strtol (input, & end, 10);
    if (end == input) {
        printf (" is not a valid number.\n");
    }
    else {
        printf (" -> %d\n", output);
    }
}

int main ()
{
    const char * number = "42";

    /* Both strtol and atoi can cope with whitespace before the
       number. */

    const char * whitespace_number = "    747";
    const char * zero = "0";
    const char * not_a_number = "cat";

    /* The function atoi can convert strings into integers, but it
       doesn't distinguish between "zero" and failure. */

    printf ("With atoi: %s -> %d %s -> %d %s -> %d %s -> %d\n",
            number, atoi (number),
            whitespace_number, atoi (whitespace_number),
            zero, atoi (zero),
            not_a_number, atoi (not_a_number));
            
    /* Use a function to run on each of these. */

    run_strtol (number);
    run_strtol (whitespace_number);
    run_strtol (zero);
    run_strtol (not_a_number);

    return 0;
}

(download)

It outputs the following:

With atoi: 42 -> 42     747 -> 747 0 -> 0 cat -> 0
With strtol, 42 -> 42
With strtol,     747 -> 747
With strtol, 0 -> 0
With strtol, cat is not a valid number.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer