Uploaded by morepatilakanksha2202

stoi

advertisement
From: https://www.udacity.com/blog/2021/05/the-cpp-stoi-function//
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 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
Download