How to convert a string to integer in C?

Learn how to convert a string to integer in c? with practical examples, diagrams, and best practices. Covers c, string, atoi development techniques with visual explanations.

Converting Strings to Integers in C: A Comprehensive Guide

Hero image for How to convert a string to integer in C?

Learn the essential methods for converting string representations of numbers into integer types in C, including atoi, strtol, and sscanf, with practical examples and best practices.

In C programming, it's a common requirement to convert a string (an array of characters) that represents a numerical value into an actual integer type. This conversion is crucial when dealing with user input, file parsing, or command-line arguments, as these are typically read as strings. C provides several standard library functions to achieve this, each with its own advantages, limitations, and error handling capabilities. Understanding these differences is key to writing robust and secure code.

The atoi() Function: Simple but Limited

The atoi() function (ASCII to integer) is part of the <stdlib.h> header and provides the simplest way to convert a string to an integer. It takes a null-terminated string as an argument and returns its integer equivalent. However, atoi() has significant limitations, particularly concerning error handling and overflow detection.

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

int main() {
    char str1[] = "12345";
    char str2[] = "-678";
    char str3[] = "abc";
    char str4[] = "123test";

    int num1 = atoi(str1);
    int num2 = atoi(str2);
    int num3 = atoi(str3);
    int num4 = atoi(str4);

    printf("\"%s\" -> %d\n", str1, num1);
    printf("\"%s\" -> %d\n", str2, num2);
    printf("\"%s\" -> %d\n", str3, num3);
    printf("\"%s\" -> %d\n", str4, num4);

    return 0;
}

Basic usage of atoi() for string to integer conversion.

The strtol() Function: Robust Conversion with Error Handling

For more robust and safer conversions, the strtol() function (string to long integer) is highly recommended. Also found in <stdlib.h>, strtol() offers comprehensive error checking, including detection of invalid characters and overflow/underflow conditions. It converts a string to a long int and allows specifying the base of the number (e.g., 10 for decimal, 16 for hexadecimal).

flowchart TD
    A[Start: Call strtol("string", &endptr, base)] --> B{Check endptr == string?}
    B -- Yes --> C[Error: No digits found]
    B -- No --> D{Check *endptr != '\0'?}
    D -- Yes --> E[Warning: Trailing characters exist]
    D -- No --> F{Check errno for ERANGE?}
    F -- Yes --> G[Error: Overflow/Underflow]
    F -- No --> H[Success: Conversion complete]
    C & E & G & H --> I[End]

Decision flow for error checking with strtol().

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

int main() {
    char str[] = "12345test";
    char *endptr;
    long val;

    errno = 0; // Clear errno before the call
    val = strtol(str, &endptr, 10);

    // Check for various error conditions
    if (endptr == str) {
        fprintf(stderr, "Error: No digits were found.\n");
    } else if (errno == ERANGE) {
        fprintf(stderr, "Error: Value out of range for long int.\n");
    } else if (*endptr != '\0') {
        fprintf(stderr, "Warning: Trailing characters found: '%s'\n", endptr);
        printf("Converted value up to invalid character: %ld\n", val);
    } else {
        printf("Successfully converted: %ld\n", val);
    }

    // To convert to int, cast the long value after validation
    if (val > INT_MAX || val < INT_MIN) {
        fprintf(stderr, "Error: Converted long value exceeds int range.\n");
    } else {
        int int_val = (int)val;
        printf("Converted to int: %d\n", int_val);
    }

    return 0;
}

Using strtol() with comprehensive error checking.

Using sscanf() for Formatted Input Conversion

The sscanf() function, from <stdio.h>, offers another flexible way to convert strings to integers, especially when dealing with strings that follow a specific format. It works similarly to scanf() but reads from a string instead of standard input. While powerful for parsing formatted data, its error handling for simple conversions can be less direct than strtol().

#include <stdio.h>

int main() {
    char str1[] = "Value: 123";
    char str2[] = "-456";
    char str3[] = "abc";
    int num;
    int result;

    result = sscanf(str1, "Value: %d", &num);
    if (result == 1) {
        printf("\"%s\" -> %d\n", str1, num);
    } else {
        printf("Failed to convert \"%s\"\n", str1);
    }

    result = sscanf(str2, "%d", &num);
    if (result == 1) {
        printf("\"%s\" -> %d\n", str2, num);
    } else {
        printf("Failed to convert \"%s\"\n", str2);
    }

    result = sscanf(str3, "%d", &num);
    if (result == 1) {
        printf("\"%s\" -> %d\n", str3, num);
    } else {
        printf("Failed to convert \"%s\"\n", str3);
    }

    return 0;
}

Example of sscanf() for string to integer conversion.