std::stoi Function in C++
Last Updated :
05 Mar, 2023
The stoi() is a standard library function that turns a string into an integer. C++ programmers utilize the function, which stands for “string to integer,” to obtain integers from strings. Additionally, the stoi() function can remove other components, such as trailing letters from the string.
Syntax:
int stoi (string s, size_t* position = 0, int base = 10)
Parameters:
- The string which has to be transformed is the first parameter.
- Location of an integer used to track how many characters were read. In that scenario, it is not used if this parameter is a null pointer.
- The third and last parameter is base. The sequence’s format determines the base used if this is 0. It uses base 10(decimal) if no argument is passed.
Examples:
Input: “1NoProgrammer”;
Output: 1
Input: “HelloWorld54”;
Output: terminate called after throwing an instance of ‘std::invalid_argument’
Explanation: This gives out an error because if first character is non-integer stoi() function terminates
Input: “You have 1keyboard”;
Output: terminate called after throwing an instance of ‘std::invalid_argument’
what(): stoi
Return Type: The string value of an argument passed to the stoi() function is returned as an integer.
How it works?
The stoi() function, which accepts a string as an argument, can convert the integer component of a string to an integer type. It will only consider integer values up to the first non-integer element or the end of the string.
When we execute the below program, an error will be produced at runtime. This is due to the fact that the stoi() function stops traversing the string when it encounters a non-integer character or a white space character. The stoi() function exits if the initial character is a non-integer.
Example:
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "GeeksForGeeks 1" ;
int n = stoi(s);
cout << n;
}
|
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
It’s giving an error because the stoi() function encounters a whitespace character before 1.
Example:
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "2009, GeeksforGeeks_founded" ;
string str1 = "0x6C1" ;
string str2 = "-10010010101" ;
int num = stoi(str);
int num_hex = stoi(str1, nullptr, 16);
int num_bin = stoi(str2, nullptr, 2);
cout << str << ": " << num << endl;
cout << str1 << ": " << num_hex << endl;
cout << str2 << ": " << num_bin << endl;
return 0;
}
|
Output
2009, GeeksforGeeks_founded: 2009
0x6C1: 1729
-10010010101: -1173
Time complexity: O(n) // n is the length of the string.
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...