C atoi() Function | Convert String to Integer

Introduction

The atoi() function in C is a standard library function that converts a string to an integer. It is part of the C standard library (stdlib.h). It is commonly used to convert string representations of integers into their corresponding integer values.

atoi() Function Syntax

The syntax for the atoi() function is as follows:

int atoi(const char *str);

Parameters:

  • str: A C string that contains the representation of an integer.

Returns:

  • The function returns the converted integer value. If no valid conversion could be performed, it returns 0.

Examples

Converting a Simple String to Integer

To demonstrate how to use atoi() to convert a string to an integer, we will write a simple program.

Example

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

int main() {
    const char *str = "12345";
    int num;

    // Convert string to integer
    num = atoi(str);

    // Print the converted value
    printf("The converted value is: %d\n", num);

    return 0;
}

Output:

The converted value is: 12345

Handling Invalid Input

This example shows how atoi() behaves with invalid input.

Example

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

int main() {
    const char *str = "abc123";
    int num;

    // Convert string to integer
    num = atoi(str);

    // Print the converted value
    printf("The converted value is: %d\n", num);

    return 0;
}

Output:

The converted value is: 0

Real-World Use Case

Converting User Input to Integer

In real-world applications, the atoi() function can be used to convert user input, provided as a string, into an integer for further numerical processing.

Example

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

int main() {
    char input[100];
    int value;

    // Prompt the user for input
    printf("Enter an integer: ");
    fgets(input, sizeof(input), stdin);

    // Convert input to integer
    value = atoi(input);

    // Print the converted value
    printf("You entered: %d\n", value);

    return 0;
}

Output (example user input "6789"):

Enter an integer: 6789
You entered: 6789

Conclusion

The atoi() function is useful for converting strings that represent integers into integer values. This function is essential when working with numerical data stored as strings.

Comments