Trusted answers to developer questions

How to convert a string to an integer in C

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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

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;
}
  • Line 2: We include stdlib.h to execute the atoi() function.

  • Lines 6-8: In this section of the code we first intialized an charactor array with the name of str in which we stored a value of 122 , and in the line 7 we converted that array to an integar with the help of atoi() function.

  • Lines 11-13: We initializes a character array str2 with the value "Hello!". Then it uses the atoi function to convert the string "Hello!" to an integer. However, since the string "Hello!" cannot be converted to a valid integer, atoi returns 0.

  • Lines 16-18: In this section we initializes a character array str3 with the value "99Hello!". Then it uses the atoi function to convert the string "99Hello!" to an integer. However, atoi stops converting when it encounters the first non-numeric character, which is 'H' in this case. So it only converts "99" to an integer, resulting in 99.

RELATED TAGS

c
conversion
string to int
atoi
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?