0
0
CHow-ToBeginner · 3 min read

How to Use atoi in C: Convert Strings to Integers Easily

In C, use the atoi function to convert a string containing digits into an integer. Include <stdlib.h> and call atoi with the string as an argument to get its integer value.
📐

Syntax

The atoi function converts a string to an integer. It is declared in the <stdlib.h> header.

  • const char *str: The input string containing the number.
  • Returns: The integer value represented by the string.
c
int atoi(const char *str);
💻

Example

This example shows how to convert a numeric string to an integer using atoi and print the result.

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

int main() {
    const char *numStr = "12345";
    int num = atoi(numStr);
    printf("The integer value is: %d\n", num);
    return 0;
}
Output
The integer value is: 12345
⚠️

Common Pitfalls

atoi does not handle errors. If the string is not a valid number, it returns 0, which can be confusing if the input is "0" or invalid. It also does not detect overflow or underflow.

For safer conversion, use strtol which provides error checking.

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

int main() {
    const char *badStr = "abc";
    int val = atoi(badStr); // returns 0, but input is invalid
    printf("atoi result: %d\n", val);

    // Safer alternative:
    char *endptr;
    long int safeVal = strtol(badStr, &endptr, 10);
    if (*endptr != '\0') {
        printf("Invalid number detected by strtol\n");
    } else {
        printf("strtol result: %ld\n", safeVal);
    }
    return 0;
}
Output
atoi result: 0 Invalid number detected by strtol

Key Takeaways

Use atoi to convert numeric strings to integers quickly in C.
atoi returns 0 for invalid inputs, so it does not detect errors.
Include <stdlib.h> to use atoi.
For safer conversions with error checking, prefer strtol over atoi.
Always ensure the input string contains a valid number before using atoi.