atoi() in C - Source Code Example

In this source code example, we will see how to use the atoi() function in C programming with an example.

atoi() Function Overview

In C programming, there are scenarios where we might need to convert a string to an integer. The atoi() function from the <stdlib.h> library serves this purpose. It parses the initial portion of the string pointed to by its argument to obtain an integer representation. 

However, be cautious: if the given string does not start with a valid integer, atoi() returns zero. It's advised to use functions like strtol() for more robust error handling, but for simple use-cases, atoi() works just fine.

Source Code Example

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

int main() {
    // Valid conversion example
    char numStr1[] = "1234";
    int num1 = atoi(numStr1);
    printf("%s as an integer: %d\n", numStr1, num1);

    // Partially valid string
    char numStr2[] = "56abc78";
    int num2 = atoi(numStr2);
    printf("%s as an integer: %d\n", numStr2, num2);

    // Invalid conversion
    char numStr3[] = "abc";
    int num3 = atoi(numStr3);
    printf("%s as an integer: %d\n", numStr3, num3);

    // String with spaces
    char numStr4[] = "   789";
    int num4 = atoi(numStr4);
    printf("'%s' as an integer: %d\n", numStr4, num4);

    return 0;
}

Output

1234 as an integer: 1234
56abc78 as an integer: 56
abc as an integer: 0
'   789' as an integer: 789

Explanation

1. In the first example, numStr1 holds a valid number as a string. atoi() successfully converts it to an integer.

2. In the second example, numStr2 begins with a number, followed by non-numeric characters. atoi() stops parsing as soon as it encounters a non-numeric character and returns the number parsed until that point.

3. numStr3 doesn't start with a number. So, atoi() returns 0.

4. For numStr4, atoi() skips the initial whitespace characters and then converts the number.

The atoi() function makes it easy to convert strings to integers, but it's essential to be aware of its limitations and behavior with different input strings.


Comments