Table of contents
1.
Introduction 
2.
C++ atoi() Function
3.
Syntax of atoi() in C++
4.
How to Convert String to Integer Using atoi() in C++?
5.
What are the Other Methods to Convert String to Integer?
6.
Using stoi() Function
7.
How to Write Your Own atoi() Function in C++?
8.
Sample Examples 
8.1.
Example 1:
8.2.
Example 2:
9.
Approach 1 
9.1.
Implementation in C++
10.
Approach 2 
10.1.
Implementation in C++
11.
Approach 3 
11.1.
Implementation in C++
12.
Frequently Asked Questions 
12.1.
Which sorting algorithm is used when we sort using STL? 
12.2.
What atoi() function in C language is present in which library? 
12.3.
What is the range of long long int? 
12.4.
Write some functions similar to atoi() functions? 
13.
Conclusion
Last Updated: Jan 19, 2025
Easy

Atoi() Function in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

In C++, the atoi() function is used to convert a string representing an integer into its corresponding integer value. The function is part of the <cstdlib> library and provides a simple way to handle string-to-integer conversions without the need for manual parsing. While atoi() can be useful in many situations, it comes with certain limitations, such as not providing error handling for invalid input. In this blog, we'll explore how the atoi() function works and its usage.

Atoi() Function in C++

C++ atoi() Function

C's atoi() function accepts a string as an input (which represents an integer) and returns an int value. In other words, the function converts a string parameter to an integer.

The atoi() function accepts only one parameter, string input, and it converts into the integer type if the string is valid and returns converted input; otherwise, it returns 0. 

Syntax of atoi() in C++

The syntax of the atoi() function in C++ is as follows:

int atoi(const char *str);
  • str is a pointer to a null-terminated string, which represents the integer you want to convert.
  • The function returns the integer value represented by the string. If the string is not a valid integer, it returns 0.

How to Convert String to Integer Using atoi() in C++?

Here’s an example of how to use the atoi() function to convert a string into an integer:

#include <iostream>
#include <cstdlib>  // For atoi()

int main() {
    const char *str = "12345";
    int num = atoi(str);  // Convert string to integer
    std::cout << "Converted integer: " << num << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Explanation:

  • The atoi() function takes the string "12345" and converts it into the integer 12345.
  • The integer result is then printed to the console.

What are the Other Methods to Convert String to Integer?

Besides atoi(), there are several other methods to convert a string to an integer in C++:

1. Using stringstream: C++ provides the stringstream class in the <sstream> library, which can be used to perform string-to-integer conversion.

2. Using stoi(): The stoi() function (introduced in C++11) is another safe and efficient method for converting strings to integers.

3. Using strtol(): The strtol() function (from <cstdlib>) provides more control and error handling compared to atoi().

Using stoi() Function

The stoi() function in C++ is another convenient way to convert a string to an integer, introduced in C++11. It offers better error handling than atoi() and throws exceptions like std::invalid_argument or std::out_of_range when the input is invalid.

Syntax:

int stoi(const std::string& str, size_t* idx = 0, int base = 10);
  • str is the string to be converted.
  • idx is an optional argument that will store the position of the first invalid character (if any).
  • base specifies the numerical base (defaults to 10 for decimal).

Example:

#include <iostream>
#include <string>  // For stoi()

int main() {
    std::string str = "12345";
    int num = std::stoi(str);  // Convert string to integer
    std::cout << "Converted integer: " << num << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Explanation:

  • The stoi() function converts the string "12345" into the integer 12345. If the string contains non-numeric characters, it throws a std::invalid_argument exception.

How to Write Your Own atoi() Function in C++?

If you want to write your own version of the atoi() function, here’s a step-by-step approach:

  • Initialize an integer variable to store the result.
  • Iterate through each character in the string.
  • Check if the character is a digit (using isdigit()).
  • Convert the character to an integer and update the result.
  • Handle negative numbers (by checking for a minus sign at the beginning).

Steps:

  • Initialize an integer variable (result = 0).
  • Loop through each character of the string.
  • For each character, check if it’s a digit:
    • Convert the digit ('0' to '9') by subtracting '0'.
    • Multiply the current result by 10 and add the digit.
  • If a negative sign is found at the beginning, multiply the result by -1 at the end.
  • Return the result.

Sample Examples 

Example 1:

Input : “123456” 
Output: 123456 
Explanation: 
In this example, we have passed "123456" as a string, and the output is 123456, which is of integer type.  

 

Example 2:

Input: “CodingNinjas” 
Output: 0
Explanation: 
In this example, we have passed "CodingNinjas" as a string, and the output is 0 because the string input is not valid. Therefore the function returns 0.

 

We will discuss different approaches to implementing atoi() function. 

Approach 1 

Initially, we will implement the atoi() function without considering any special case. 

  • Initialize the ans = 0. 
  • Start traversing the string or character array and update the ans for each character one by one. 
  • For every character update the answer as ans = ans *10 + (s[i] - ‘0’).  
  • Finally, return the ans after traversing the complete string.

Implementation in C++

#include<bits/stdc++.h>

using namespace std;
int atoi(string s) {
  // initialise ans = 0
  int ans = 0;
  // traverse the complete string
  // take ascii value of numeric string
  // and update the result
  for (int i = 0; i < s.size(); i++) {
    ans = ans * 10 + (s[i] - '0');
  }
  // finally return the ans.
  return ans;
}

int main() {
  string s = "123456";
  cout << atoi(s) << endl;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

123456 

 

Try and compile by yourself with the help of online C++ Compiler for better understanding.

Approach 2 

We will now handle the negative integer strings as well. If the input string is negative, store this in a flag variable and convert the remaining integer string using the previous approach. When returning the ans, check if the string was negative, and multiply the result with -1. Otherwise, return the answer. 

Implementation in C++

#include<bits/stdc++.h>

using namespace std;
int atoi(string s) {
  // initialise ans = 0
  int ans = 0;
  // check for negative string
  bool flag = false;
  // declaring i, to traverse the string
  int i = 0;
  
  // if the number is negative, mark flag as true
  // and move the pointer i, by one.
  if (s[i] == '-') {
    flag = true;
    i++;
  }

  // traverse the complete string
  // take ascii value of numeric string
  // and update the result
  for (i; i < s.size(); i++) {
    ans = ans * 10 + (s[i] - '0');
  }
  // finally return the ans.
  return flag == true ? ans * -1 : ans;
}
int main() {
  string s = "-123456";
  cout << atoi(s) << endl;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

-123456

Also read, Application of Oops

Approach 3 

After implementing negative integers, we will take more corner cases while implementing the atoi() function. Let's look at the different corner cases. 

  1. Discarding all leading Whitespaces: It may be possible that strings contain leading white spaces in input. We should remove them, as they do not have any role in output. 
  2. Overflow: We will check if the input string is in the range or not because the range of the integers is from INT_MIN to INT_MAX. If the input is greater than INT_MAX/10, return INT_MAX; if the sign is positive, otherwise return INT_MIN. 
  3. Invalid Input: If the input string is invalid, then simply returns 0. 

Implementation in C++

#include<bits/stdc++.h>

using namespace std;
int atoi(string str) {
  // declaring the i to traverse the string
  // ans variable to store the final answer  
  int i = 0, ans = 0;
  // declaring the flag variable
  // to check if the input is negative or not
  // if input is negative then isNegative variable is true
  // otherwise false
  bool isNegative = false;
  
  // removing the white spaces
  if (str[i] == ' ') {
    i++;
  }
  
  // checking the sign of the input
  if (str[i] == '-' || str[i] == '+') {
    if (str[i] == '-') {
      isNegative = true;
    }
    i++;
  }
  
  for (i; i < str.size(); i++) {
    // if the number is out of range, then return INT_MAX if the input is positive
    // otherwise return INT_MIN if the input is negative.
    if (ans > INT_MAX / 10) {
      if (isNegative) {
        return INT_MIN;
      } else {
        return INT_MAX;
      }
    }
    
    // checking for validity of the input
    // if input is something other than numbers
    // then simply return 0
    if (str[i] < '0' || str[i] > '9') {
      return 0;
    }
    
    // finally if the input is correct
    // add it to the ans
    ans = ans * 10 + str[i] - '0';
  }
  return isNegative ? ans * -1 : ans;
}
int main() {
  string s = "CodingNinjas";
  cout << atoi(s) << endl;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

0 

Frequently Asked Questions 

Which sorting algorithm is used when we sort using STL? 

The sorting algorithm used in STL sort() is IntroSort. Intersport is a hybrid sorting algorithm that uses three sorting algorithms to minimize the running time. These algorithms are quicksort, Heapsort, and Insertion Sort.

What atoi() function in C language is present in which library? 

The C programming language's atoi() function translates a string to an integer numerical representation. ASCII to integer is abbreviated as atoi. It's in the 'stdlib' header file of the C standard library.

What is the range of long long int? 

The range of long long int is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. 

Write some functions similar to atoi() functions? 

Some functions similar to atoi() function are:  
→ atof function <stdlib.h>
→ atol function <stdlib.h>
→ strtol function <stdlib.h>
→ Cstrtoul function <stdlib.h>

Conclusion

In this article, we discussed the introduction of the atoi() function, discussed some sample examples, and approaches to implementing the atoi() function. 

Recommended Readings:

Live masterclass