0
0
CHow-ToBeginner · 2 min read

C Program to Convert String to Integer

In C, you can convert a string to an integer using the atoi() function like int num = atoi(str); or the safer strtol() function for better error handling.
📋

Examples

Input"123"
Output123
Input"-456"
Output-456
Input"0"
Output0
🧠

How to Think About It

To convert a string to an integer in C, you read the characters of the string and interpret them as digits. The atoi() function does this automatically by scanning the string until it finds non-digit characters. For safer conversion, strtol() lets you check if the entire string was valid and handle errors.
📐

Algorithm

1
Get the input string containing digits.
2
Use a conversion function like <code>atoi()</code> or <code>strtol()</code> to parse the string.
3
Store the returned integer value.
4
Use the integer in your program.
💻

Code

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

int main() {
    char str[] = "12345";
    int num = atoi(str);
    printf("Converted number: %d\n", num);
    return 0;
}
Output
Converted number: 12345
🔍

Dry Run

Let's trace converting the string "12345" using atoi.

1

Input string

str = "12345"

2

Call atoi

num = atoi(str)

3

Result

num = 12345

StepStringInteger Result
1"12345"N/A
2"12345"12345
💡

Why This Works

Step 1: Using atoi

The atoi() function reads the string from left to right and converts digit characters into an integer value.

Step 2: Handling non-digit characters

atoi() stops converting when it encounters a non-digit character, ignoring the rest.

Step 3: Safer alternative

strtol() allows checking if the entire string was valid and handles errors better than atoi().

🔄

Alternative Approaches

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

int main() {
    char str[] = "12345";
    char *endptr;
    long num = strtol(str, &endptr, 10);
    if (*endptr == '\0') {
        printf("Converted number: %ld\n", num);
    } else {
        printf("Invalid input\n");
    }
    return 0;
}
strtol provides error checking by using endptr to detect invalid characters.
Manual conversion
c
#include <stdio.h>

int stringToInt(const char *str) {
    int result = 0;
    int sign = 1;
    if (*str == '-') {
        sign = -1;
        str++;
    }
    while (*str >= '0' && *str <= '9') {
        result = result * 10 + (*str - '0');
        str++;
    }
    return sign * result;
}

int main() {
    char str[] = "12345";
    int num = stringToInt(str);
    printf("Converted number: %d\n", num);
    return 0;
}
Manual conversion gives full control but requires careful coding to handle errors.

Complexity: O(n) time, O(1) space

Time Complexity

The conversion scans each character of the string once, so it takes linear time proportional to the string length.

Space Complexity

The conversion uses constant extra space since it only stores the integer result and a few variables.

Which Approach is Fastest?

atoi() is fastest but unsafe; strtol() is slightly slower but safer; manual conversion is flexible but more complex.

ApproachTimeSpaceBest For
atoiO(n)O(1)Simple quick conversion without error checking
strtolO(n)O(1)Safe conversion with error detection
Manual conversionO(n)O(1)Custom parsing and full control
💡
Use strtol() instead of atoi() for safer string to integer conversion with error checking.
⚠️
Beginners often forget that atoi() does not handle invalid input and can cause undefined behavior if the string is not a valid number.