How to use C++ STL stoi() function In C++
stoi() is an STL function in c++ that is used to convert any number(binary, octal, hexadecimal) to an unsigned integer in a specified base. It is defined in the <string> header file. It contains three parameters:
- First is the string name, which means the string that you want to convert into decimal.
- Second is an index number, by default, it’s 0, or you can initialize it with nullptr.
- The last one is the base of the input string. It is also an optional parameter. By default, it’s 10.
This function returns an integer value of the given hex string.
Syntax:
int stoi (const string& str, [size_t* idx], [int base]);
Below is the C++ program to implement stoi() function to convert a hex string to an integer:
C++
// C++ program to implement stoi() // function to convert a hex string // to an integer #include <iostream> #include <string.h> using namespace std; // Driver code int main() { // Input string string s = "DD" ; // Initializing the return integer // value of the function to a new // variable int ans = stoi(s, 0, 16); cout << ans << endl; return 0; } |
221
Different Ways to Convert Hex String to Integer in C++ STL
A hexadecimal number is a number whose base is 16. has numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. And 10, 11, 12, 13, 14, and 15 these numbers are denoted by A, B, C, D, E, F. In C++ STL there are certain properties that help to convert a hexadecimal string or number to a decimal number easily.
There are 5 different ways to convert a Hex string to an Integer in C++:
- Using stoi() function
- Using sscanf() function
- Using stoul() function
- Using string stream method
- Using boost:lexical_cast function
Let’s start discussing each of these methods in detail.