Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
conversion
string to int
atoi

How to convert a string to an integer in C

Educative Answers Team

In C, the atoi() function converts a string to an integer.

svg viewer

Syntax

The syntax for the function is given below:

int atoi(const char *string)

Parameters

The function takes as input the string that is to be converted to an integer.

Return value

  1. If successfully executed, the function returns the integer value.

  2. If the string starts with an alphanumeric character or only contains alphanumeric characters, 0 is returned.

  3. In case the string starts with a numeric character but is followed by an alpha-numeric character, the string is converted to an integer until the occurrence of the first alphanumeric character

Note: The stdlib.h library must be included for the atoi() function to be executed

Example

Let’s look at an example to further understand the working of the atoi() function:

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

int main() {
    // Converting a numeric string
    char str[10] = "122";
    int x = atoi(str);
    printf("Converting '122': %d\n", x);

    // Converting an alphanumeric string
    char str2[10] = "Hello!";
    x = atoi(str2);
    printf("Converting 'Hello!': %d\n", x);

    // Converting a partial string
    char str3[10] = "99Hello!";
    x = atoi(str3);
    printf("Converting '99Hello!': %d\n", x);
    return 0;
}

RELATED TAGS

c
conversion
string to int
atoi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring