How to convert a string to an integer in C?

Converting a string to an integer is a common operation in C programming, especially when dealing with user input or external data.

The process involves parsing a sequence of characters representing a numerical value and converting it to its integer equivalent.

In this comprehensive guide, we'll explore various methods for string to integer conversion in C, covering standard library functions, custom implementations, and best practices.

Table of Contents #

  1. Introduction to String to Integer Conversion
  2. Using Standard Library Functions
  3. Custom String to Integer Conversion
  4. Handling Errors and Edge Cases
  5. Conclusion

1. Introduction to String to Integer Conversion

Converting a string to an integer is a crucial task in C programming, often required for tasks like processing user input, reading configuration files, or handling external data.

The goal is to extract the numerical value encoded in a string and store it as an integer for further processing.

2. Using Standard Library Functions

2.1 atoi Function

The atoi (ASCII to Integer) function is a standard library function that converts a string of digits to an integer. It stops conversion when it encounters the first non-digit character.

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

int main() {
    char str[] = "12345";
    int result = atoi(str);

    printf("Converted integer: %d\n", result);

    return 0;
}

2.2 strtol Function

The strtol (String to Long) function is a more versatile function that allows better error handling.

It can convert a string to a long integer and provides a pointer to the first invalid character.

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

int main() {
    char str[] = "12345";
    char *endptr;
    long result = strtol(str, &endptr, 10);

    if (*endptr != '\0') {
        printf("Conversion failed. Invalid character: %c\n", *endptr);
    } else {
        printf("Converted integer: %ld\n", result);
    }

    return 0;
}

3. Custom String to Integer Conversion

While standard library functions are convenient, understanding the process allows for custom implementations.

Here's a simple function that converts a string to an integer:

#include <stdio.h>

int customAtoi(const char *str) {
    int result = 0;
    int sign = 1;  // Positive by default

    // Handle optional sign
    if (*str == '-') {
        sign = -1;
        ++str;
    } else if (*str == '+') {
        ++str;
    }

    // Process each digit
    while (*str >= '0' && *str <= '9') {
        result = result * 10 + (*str - '0');
        ++str;
    }

    return sign * result;
}

int main() {
    char str[] = "-9876";
    int result = customAtoi(str);

    printf("Converted integer: %d\n", result);

    return 0;
}

4. Handling Errors and Edge Cases

String to integer conversion may encounter various errors, such as invalid characters, overflow, or underflow.

It's essential to handle these situations to ensure robust and reliable code.

4.1 Overflow and Underflow

When converting a large string to an integer, there is a risk of overflow. It's crucial to check the result against the limits of the int data type.

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

int safeAtoi(const char *str) {
    long result = 0;
    int sign = 1;

    if (*str == '-') {
        sign = -1;
        ++str;
    } else if (*str == '+') {
        ++str;
    }

    while (*str >= '0' && *str <= '9') {
        result = result * 10 + (*str - '0');

        // Check for overflow
        if (result > INT_MAX) {
            fprintf(stderr, "Overflow occurred. Cannot convert.\n");
            return sign == 1 ? INT_MAX : INT_MIN;
        }

        ++str;
    }

    return sign * (int)result;
}

int main() {
    char str[] = "2147483648";  // One more than INT_MAX
    int result = safeAtoi(str);

    printf("Converted integer: %d\n", result);

    return 0;
}

4.2 Invalid Character Handling

When encountering an invalid character in the string, it's essential to handle the error appropriately.

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

int safeAtoi(const char *str) {
    long result = 0;
    int sign = 1;

    if (*str == '-') {
        sign = -1;
        ++str;
    } else if (*str == '+') {
        ++str;
    }

    while (*str >= '0' && *str <= '9') {
        result = result * 10 + (*str - '0');
        ++str;
    }

    // Check for characters other than digits
    if (*str != '\0') {
        fprintf(stderr, "Conversion failed. Invalid character: %c\n", *str);
        return 0;  // Return an error value
    }

    // Check for overflow
    if (result > INT_MAX) {
        fprintf(stderr, "Overflow occurred. Cannot convert.\n");
        return sign == 1 ? INT_MAX : INT_MIN;
    }

    return sign * (int)result;
}

int main() {
    char str[] = "123abc";
    int result = safeAtoi(str);

    if (result != 0) {
        printf("Converted integer: %d\n", result);
    }

    return 0;
}

5. Conclusion

Converting a string to an integer is a common task in C programming, and there are multiple approaches to achieve this.

Standard library functions like atoi and strtol provide convenient solutions, while custom implementations offer more control and understanding of the process.

When performing string to integer conversion, it's crucial to handle errors and edge cases to ensure the reliability and robustness of the code.

By mastering the techniques presented in this guide, C programmers can confidently and accurately convert strings to integers in various programming scenarios.