Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is stoi() in C++?
3.
Syntax of stoi() in C++
3.1.
C++
4.
Parameters of stoi Function in C++
5.
What is the return value of stoi?
6.
How To Use the C++ STOI Conversion
6.1.
C++
6.2.
C++
7.
When To Use String to Int in C++
8.
Time to Avoid Using String to Int
9.
Frequently Asked Questions
9.1.
What is the stoi in C++?
10.
What is stol in C++?
10.1.
What is the difference between atoi and stoi in C++?
11.
Conclusion
Last Updated: Sep 22, 2024
Easy

Stoi In C++

Author Pallavi singh
0 upvote

Introduction

Imagine going on a trip, and you want to go to multiple countries. If you're a traveller, you must carry some money with you. For this reason, you must take a currency which you can use internationally. You can use that money and convert it to the country you're stepping in. STOI kind of works in a similar way. Programmers prefer to avoid parsing string inputs for integer values. It is mainly because another section of their code needs these values. Fortunately, the function of STOI in C++ turns numeric strings into integers. STOI also offers some capabilities for removing unwanted string material, such as trailing characters. 

Today, we will look at the function of STOI in C++. We will also see when it's good to use it.

Stoi in C++

Also see, Literals in C.

What is stoi() in C++?

The function of stoi in C++ converts a string to an integer value. The function is an abbreviation for "string to integer,". This means that C++ programmers use it to extract integers from strings. The stoi() function is very new. To simply compare, STOI have been added to the language in one of its most recent versions in 2011, which was C++11.

Syntax of stoi() in C++

int stoi (string s, size_t* position = 0, int base = 10)

 

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

Following that, we have to specify the identification for the number's starting position. This is within the string that has to be processed.

int base specifies the string's numerical base. In simple words, there are two for binary, sixteen for hexadecimal, and ten for base ten.

If we're working with a different base set than base 10, the only requirement we need is the string alone. We'll look at examples of hexadecimal and binary numbers later.

As now we will see below, stoi() is simple to use:

  • C++

C++

#include <iostream>
#include <string>


using namespace std;


int main() {
   string 1stString = "222";
   int a = stoi(1stString);
   cout << "stoi(\"" << 1stString << "\") is " << a << '\n';
}
You can also try this code with Online C++ Compiler
Run Code

As we can see, we start by declaring a string with the value 222 and the string as 1stString. We transform this string to an integer with stoi() and then print it with cout.

And now, we get the output:

stoi("222") is 222

If we are using a version of C++ which is older than C++11 (for example, C++03), the stoi() function will be unavailable. Which means we will not be able to use it. Instead, we must utilise the stringstream class that we can get in the C++ standard library.

Now that we got the idea of STOI in C++, let's now get a bit more serious and explore how to use STOI in C++.

Also Read - C++ Interview Questions

Parameters of stoi Function in C++

  1. str (const string&): The input string to be converted to an integer.
  2. pos (size_t):* A pointer to a size_t object where the position of the first unconverted character is stored. It is optional and can be set to nullptr if not needed.
  3. base (int): An optional parameter specifying the number base (radix) for the conversion. It can be 0 or in the range 2-16. If set to 0, the base is determined by the prefix of the input string (e.g., "0x" for hexadecimal).

What is the return value of stoi?

In C++, the std::stoi function is used to convert a string to an integer. The return value of std::stoi is an integer that represents the converted value of the input string.

How To Use the C++ STOI Conversion

Now we will see How To Use the C++ String to Integer STOI Conversion.

Except for one big problem, the stoi() function works well at extracting integers from strings. stoi in C++ is unaffected by + or - signs, zeros in front of numbers, hexadecimal prefixes (0x or 0X), or blank characters, which are also known as whitespace.

The fact that if other characters follow the number does not matter to stoi():

  • C++

C++

#include <iostream>
#include <sstream>


using namespace std;


int main()
{
string 1stString = "-222";
string 2ndString = "222abc";
string 3rdString = "0000000222";
string 4thString = "3.14159";


int 1stNum = stoi(1stString);
int 2ndNum = stoi(2ndString);
int 3rdNum = stoi(3rdString);
int 4thNum = stoi(4thString);



cout << "1stNum: " << 1stNum << endl;
cout << "2ndNum: " << 2ndNum << endl;
cout << "3rdNum: " << 3rdNum<< endl;
cout << "4thNum: " << 4thNum;
}
You can also try this code with Online C++ Compiler
Run Code

This example returns the following:

1stNum: -222
2ndNum: 222
3rdNum: 222
4thNum: 3

As shown in this example, stoi does seem much more concerned about the minus sign in string "1stString". Cuts off the letters after 222 in the string "2ndString". And then gets rid of all those unsightly zeros for us in string "3rdString". String "4thString" gets shortened and loses everything after the decimal point since stoi returns integers.

However, we should know that this only works when letters follow the integer characters.

Our programme gives us an error when a letter comes before a digit in a string.

Let us take a look at them.

  • C++

C++

#include <iostream>
#include <sstream>


using namespace std;


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


int 1stNum = stoi(1stString);


cout << "1stNum: " << 1stNum;
}
You can also try this code with Online C++ Compiler
Run Code

Because stoi cannot accept the characters before the number in the string, running code based on the examples above results in a "std::invalid_argument" error.

Must Read Lower Bound in C++

When To Use String to Int in C++

When we need user input in the form of a string and need to extract an integer from that string, a string to int is useful. Maybe the user is listing their address, and we simply want to use the address number someplace else in the programme. stoi can split those home numbers for whatever reason we require.

Another area in which stoi excels is with file inputs. File access functions frequently provide strings to work with. The stoi function may extract the integers from those strings from the file input.

Consider a programme that reads a file containing a list of transactions as a set of strings. The stoi function may parse the strings and extract the dollar amounts as integers for further calculation and analysis.

Time to Avoid Using String to Int

We should take note that, in some cases, converting a string to an int in C++ is unnecessary. Under some conditions, we can configure the programme to immediately read an integer. Instead of having the user enter something as a string, we can have the user enter an integer using the "std::cin" variable.

Check out this article - C++ String Concatenation


Must Read Non-alphanumeric Characters

Frequently Asked Questions

What is the stoi in C++?

The stoi function in C++ converts a string to an integer, handling various numeric formats and optionally returning the position of the first unconverted character.

What is stol in C++?

The stol function in C++ converts a string to a long integer, similarly offering error checking and position tracking of unprocessed characters.

What is the difference between atoi and stoi in C++?

atoi is a legacy C function that converts a string to an integer without error checking, while stoi is a C++ function with exceptions for invalid inputs.

Conclusion

In the article, we read about STOI in C++. We took an idea of what it is and saw examples. We also read about when and when not to use it, as we might have an alternate way. Refer to our courses and explore Coding Ninjas Studio to find more exciting stuff. You can also look into the interview experiences and solve different problems. Look into our Guided paths, test series, libraries and resources to know more.

Recommended Reading: 

Turbo C++

Live masterclass