Atoi in C++ is a predefined function from the cstdlib header file used to convert a string value to an integer value. There are many scenarios where you might need to convert a string with an integer value to an actual integer value, and that’s where the C++ atoi() function comes in.

C++ atoi() Function

The atoi() function in C++ is defined in the cstdlib header. It accepts a string parameter that contains integer values and converts the passed string to an integer value. If the string is null or has any non-integer value, atoi in C++ silently fails the execution without throwing any error or exception.

Syntax of atoi in C++

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

int atoi (const char * str);

Parameters of atoi in C++:

The C++ atoi() function accepts only a single parameter, which is:

  • str: The string that needs to be converted to an integer value

Return Value of atoi in C++

The atoi() function returns the converted integer value if the execution is successful. If the passed string is not convertible to an integer, it will return a zero.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

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

You can use the atoi in C++ to convert a string to an integer value. You need to implement the cstdlib header file and pass the string that you want to convert to an integer. The code below demonstrates how to convert a string to an integer using atoi in C++.

#include <iostream>

#include <cstdlib>

#include <string> 

using namespace std;

int main(){

  // Strings to be used for conversion

  const char* str1 = "200";

  const char* str2 = "1.252";

  const char* str3 = "Welcome";

  const char* str4 = "100 Welcome";

  // using atoi() in C++

  int i1 = atoi(str1);

  int i2 = atoi(str2);

  int i3 = atoi(str3);

  int i4 = atoi(str4);

  cout << "Integer 1 is : " << i1 << endl;

  cout << "Integer 2 is : " << i2 << endl;

  cout << "Integer 3 is : " << i3 << endl;

  cout << "Integer 4 is : " << i4 << endl;

}

Output:

Atoi_in_Cpp_1

As you can see in the output, it converted the first two strings with integer values to integers. However, the third string didn’t have any convertible integer value. Hence, the result for converting the third string was 0. The fourth string had both integer value “100” and a character sequence “Welcome.” In this scenario, atoi in C++ converted the possible integer value 100 and showed it as the output, whereas the string “Welcome” was ignored.

What are the Other Methods to Convert String to Integer?

Besides the C++ atoi() function, there are other ways to convert a string to an integer. Some of the alternative methods for this type of conversion are mentioned below.

Using StringStream Class

Defined in the iostream header, the C++ StringStream class allows input, output, and clear operations on string-based streams. The cout, cin, and their respective equivalents << and >> are used for extracting data from and inserting it into the streams. Here’s an example to show how to convert a string to an integer using StringStream class.

#include <iostream>

#include <sstream>

using namespace std;

int main(){

    string s = "10";

    int i;

    // using stringstream class to insert string and

    // extract int values

    stringstream ss;

    ss << s;

    ss >> i;  

    cout << "String Value: " << s << endl;  

    cout << "After converting to integer, the value is: " << i << endl;  

}

Output:

Atoi_in_Cpp_2

As you can see in the output, it converts the string s with the value “10” to an integer value of 10.

Using stoi() Function

C++ stoi() function is almost similar to the atoi() function with one major difference. While the atoi() function returns 0 if the string is not convertible, the stoi() function will simply throw an exception. Here’s an example of converting a string to an integer using the stoi() function.

#include <iostream>

#include <string> 

using namespace std;

int main() {

    string s1 = "200";

    string s2 = "1.252";

    string s3 = "100 Welcome";

    // using the stoi() function for conversion

    int i1 = stoi(s1);

    int i2 = stoi(s2);

    int i3 = stoi(s3);

    cout << "Integer i1 is : " << i1 << endl;

    cout << "Integer i2 is : " << i2 << endl;

    cout << "Integer i3 is : " << i3 << endl;

}

Output:

Atoi_in_Cpp_3

As you can see in the output, the results were similar to those given by the atoi() function. However, if you add a string that is not convertible, it will throw an error. Here’s an example:

#include <iostream>

#include <string> 

using namespace std;

int main() {

    string s1 = "200";

    string s2 = "1.252";

    string s3 = "100 Welcome";

    string s4 = "Welcome";

    // using the stoi() function for conversion

    int i1 = stoi(s1);

    int i2 = stoi(s2);

    int i3 = stoi(s3);

    int i4 = stoi(s4);

    cout << "Integer i1 is : " << i1 << endl;

    cout << "Integer i2 is : " << i2 << endl;

    cout << "Integer i3 is : " << i3 << endl;

    cout << "Integer i4 is : " << i4 << endl;

}

Output:

Atoi_in_Cpp_4

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

Besides the predefined atoi in C++, you can also create your own atoi() function. Here are the fundamental steps to create your own atoi() function in C++.

  1. Initialize the integer variable as 0.
  2. Take a single character from the string each time and add the number to the previous result after multiplying it by two.
  3. Check if the string is convertible by checking if the characters lie between 0 and 9.
  4. Check for a - sign at the beginning for the negative value and multiply the result by -1.

If the steps are not helping, the examples below certainly will. Here’s how to create your own atoi in C++.

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Example 1: Simple atoi in C++ to Convert String to Integer

#include <iostream>

using namespace std;

// Creating your own atoi() function

int myAtoi_Func(char* s){

// Step 1

int result = 0;

// Step 2

for (int x = 0; s[x] != '\0'; ++x)

result = result * 10 + s[x] - '0';

return result;

}

int main(){

char s[] = "12354";

    // Calling the function

int i = myAtoi_Func(s);

cout << i;

return 0;

}

Output:

Atoi_in_Cpp_5

Example 2: Converting Negative Value and Checking if the String Is Convertible

In this example, you will create your own atoi in C++ that will check if the string is convertible, is negative, and then complete the conversion based on the results.

#include <stdio.h>

#include <iostream>

using namespace std;

// Checking if c is numeric

// Step 3

bool isNumeric(char c){

return (c >= '0' && c <= '9') ? true : false;

}

// atoi() function that returns 0 if c is non-convertible

int myAtoi_Func(char* s){

if (*s == '\0')

return 0;

// Step 1

int result = 0;

    //Initializing the positive sign

int sign = 1;

// Initializint the index of first digit

int i = 0;

// Checking if number is negative and updating the sign accordingly

if (s[0] == '-')

{

sign = -1;

// Updating the index of first digit

i++;

}

// Iterating through all digits and updating result

for (; s[i] != '\0'; ++i)

{

// Error messages

if (isNumeric(s[i]) == false)

return 0;

result = result * 10 + s[i] - '0';

}

// Returning the result

return sign * result;

}

int main(){

char s[] = "-524";

int val = myAtoi_Func(s);

printf("%d ", val);

return 0;

}

Output:

Atoi_in_Cpp_6

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Wrapping it up

In this article, you learned about atoi in C++. Now you know what the C++ atoi() function does and how you can create your own atoi. Understanding how to convert a string into an integer will come in handy while developing complex programs. Atoi in C++ is just one of the many fundamental concepts of C++ programming. You can refer to Simplilearn’s C++ Tutorial for Beginners to learn about the other basic concepts such as for loop and array.

You can also learn by signing up on our SkillUp platform. The platform offers numerous free online courses for various programming languages, including C++. You can sign up and choose any course according to your preference to hone your skills and understanding in that particular programming language.

Full-stack developers are in much higher demand than professionals with expertise in a single language. Hence, it is essential to get mastery in multiple programming languages now more than ever. Our Full Stack Developer - MERN Stack is created to cater to this very need. The course helps learn about more than 30 programming skills and tools with hours of applied learning, hands-on practice, and learning materials. It also gives you a completion certificate to help you land a lucrative job in the software development field. Head on to the above link and opt for the course if you want to pursue a career in development.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you ASAP!