C++ - C++ STOI - Programming Languages

The C++ STOI Function Explained

No developer wants to parse string inputs for integer values, simply because they need these values for another part of their program. Luckily, C++ has a stoi function that converts numeric strings to integers. stoi also has some functionality for getting rid of other material in the string, such as trailing characters.

In this article, we’ll provide an overview of the stoi function in C++ and when it’s most appropriate to use.

What Is stoi() in C++?

In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011. 

To use stoi, you’ll need to provide specific criteria for the function:

stoi(string, position, int base)

The first criterion is the string that needs to be converted.

Next, we’ll need to specify the identifier for the starting position of the number within the string that needs to be parsed.

int base defines the numerical base for the string. As examples, we have 2 for binary, 16 for hexadecimal, and 10 for base 10.

Unless working with a base set other than base 10, the only criterion we require is the string itself. We’ll see examples for hexadecimal and binary numbers a bit later.

stoi() is straightforward to use, as we’ll see below:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str1 = "123";
    int x = stoi(str1);
    cout << "stoi(\"" << str1 << "\") is " << x << '\n';
}

As you can see, we first declare a string, str1, with the value 123. We use the stoi() function to convert this string into an integer and then use cout to output it. Here’s the result:

stoi("123") is 123

If you’re using an older version of C++ that’s locked to pre-C++11 (e.g., C++03), the stoi() function won’t be available to use. Instead, you’ll need to use the stringstream class located in the C++ standard library. Here’s how we use stringstream:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    string str1 = "123";
    stringstream container(str1);
    int x;
    container >> x;
    cout << "Value of x: " << x;
}

As you can see, we still declare the str1 to be 123, but then we have to use stringstream instead of stoi. stringstream allows us to place str1 into an object that, in this example, is named container

Next, we declare an integer x, but this integer can be any value as we’re going to replace it shortly. We use a right shift (>>) to slide the string value stored in the object container to replace the integer previously stored in x.

Finally, we can use cout to output the value of x, which is our original string. Running the code gives us:

Value of x: 123

That wasn’t so bad, was it? Let’s now go deeper and examine a few to use C++ STOI.

How To Use the C++ String to Integer (STOI) Conversion

The stoi() function works well at pulling integers out of strings save for one major hiccup, which we’ll see below. stoi() can handle + or – signs, zeros at the front of a number, hexadecimal prefixes (0x or 0X) and whitespace characters without issue. stoi() does not even care if other characters follow the number:

#include <iostream>
#include <sstream>

using namespace std;

int main() 
{
string s1 = "-123";
string s2 = "123xyz";
string s3 = "000000000000123";
string s4 = "3.14159";

int num1 = stoi(s1);
int num2 = stoi(s2);
int num3 = stoi(s3);
int num4 = stoi(s4);


cout << "num1: " << num1 << endl;
cout << "num2: " << num2 << endl;
cout << "num3: " << num3 << endl;
cout << "num4: " << num4;
}

This example returns the following:

num1: -123
num2: 123num3: 123num4: 3

As this example shows, stoi does not mind the minus sign in string s1, chops off the characters we see after 123 in string s2, and removes all those unsightly zeros for us in string s3. Since stoi returns integers, string s4 is truncated and loses everything after the decimal point.

However, this only works in cases where letters appear after the integer characters. For strings where a letter precedes a digit, our program throws an error. Let’s have a look:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
string s1 = "The answer is 7";

int num1 = stoi(s1);

cout << "num1: " << num1;
}

Running code that’s based on the examples above returns a std::invalid_argument error because stoi cannot handle the characters before the number in the string.

When To Use String to Int in C++

Using string to int is beneficial when you require user input in the form of a string, and you need to extract an integer from that string. Perhaps the user is listing their address, and you want to use only the address number somewhere further in your program. stoi can separate those house numbers for whatever reason you might need.

Another instance where stoi shines is in regards to file inputs. Often, file access functions will give strings to work with. The stoi function can take those strings from the file input and extract the integers for later use.

For example, consider a program that inputs a file with a list of transactions as a set of strings. The stoi function can take those strings and pull out the dollar values as integers for calculation and analysis.

When To Avoid Using String to Int in C++

There are instances where converting a string to int in C++ is not necessary. Under certain circumstances, you can set up your program to simply read an integer right away. Instead of having a user input something as a string, you can use the std::cin variable to have the user input an integer. Here’s an example:

#include <iostream>

using namespace std;

int main()
{
        cout << "Enter your age: ";
        int x{ };
        cin >> x;
        cout << "Your age is " << x << '\n';
    return 0;
}

This program starts off by outputting a command to the user, looking for the user’s age. The code is set up using int x{ } to capture that input as an integer value. As long as the user puts in a valid response, this code shifts that integer to our variable x, and then outputs that back to the user. Should a user put in a floating-point number, this program will truncate the number and return only the integer.

Assuming the user listed “25” at their age, we’ll see the following output:

Your age is 25

Other Number Parsing Functions in C++

When it comes to parsing numbers, C++11 introduced a few other functions to use in specific scenarios.

The first, stoul, works much like stoi except that stoul converts a string into an unsigned integer. The stoul function does so by returning the original string as an unsigned long value.

stof and stod work similarly to stoul but convert a string to a floating-point number or a double, respectively. These functions let programmers go beyond the realm of just integers and work with decimal numbers as well.

Converting a Non-Base 10 String Into an Integer

Early on, we talked about using stoi to read non-base ten strings. Let’s see how stoi works with a hexadecimal example:

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
      string str = "FF";
      unsigned long num = stoi(str,nullptr,16);
      cout << "The base ten equivalent of FF is " << num << "\n";
}

Here, we use the hexadecimal string “FF.” We do need to let the stoi function know that the string has a hexadecimal base (hence the 16 in the int base slot). We get an output of:

The base 10 equivalent of FF is 255


Similarly, we can likewise use stoi for binary strings:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string bin_string = "10101010";
int number = 0;
number = stoi(bin_string, nullptr, 2);
cout <<"Original binary string: "<< bin_string << endl;
cout <<"Equivalent integer: "<< number << endl;
}

At this point, we need to change our base value from the default 10 to a 2 to represent our binary string. We get the following output:

Original binary string: 10101010
Equivalent integer: 170


Become a C++ Developer

In this guide to C++ STOI, we’ve barely scratched the surface of the amazing capabilities of the C++ language. Why not go further?

Our C++ nanodegree program takes you through a hands-on curriculum that’s designed to turn you into a fully fledged C++ developer.

Enroll in Udacity’s C++ Nanodegree program today!

Start Learning