Hit enter after type your search item

C++ stoi() Function to Convert String to int [5 Examples]

What is stoi() function in C++?

The stoi function:

  • The stoi() is the abbreviation of “string to an integer”.
  • As the full name suggests, stoi() is used to convert string to int in C++
  • stoi() function was introduced in C++ 11

Why do we need stoi() function?

This is quite common in different languages to convert one data type to another. This is generally called type casting.

One of the examples can be converting user entered strings into numbers to ensure the operation goes smoothly and the program does end up in error.

An example of converting a string to int by stoi() function

In the first example, we have declared a string with a number. i.e. str = “425”;

Then we used stoi() function to convert this string into an int and assigned it to an integer variable and displayed its value:



Taking user input string example

For this program, we take the user input and store in the string variable.

Sample Output:


What as I entered the alphabet i.e. ABC as input?



So, the string you are trying to convert to int should be numbers enclosed in double quotes. Otherwise, the above error is generated.

Using stoi() to convert hex string to int example

The stoi() function can also be used for converting hex string to int. In fact, you may convert strings in other formats like:

  • simple numbers (as seen in the above examples)
  • binary
  • octal
  • hex

stoi() function syntax is:

    int stoi (const string&  str, [size_t* idx], [int base]);

The example below shows using the stoi() function for converting a hex string to int:



A C++ program for converting binary string to int

Similarly, you may convert binary string to int by using stoi() function as shown in an example below:




This div height required for enabling the sticky sidebar