How to use stoi function In C++

stoi is a function in the string header file. The function takes as an argument a string and returns the converted integer. The function syntax is as follows:

Syntax:

int stoi (char *str, size_t* idx, int base);

Here,

str: The input string that is to be converted
size: Pointer to the object whose value is set by the function
base: It specifies the radix to determine the value type of input string

Since the requirement is to convert the Hex string to an Integer, the base would be 16.

Example:

C++




// C++ program to implement
// stoi() function to convert
// hex string to signed integer
#include <iostream>
#include <string>
using namespace std;
 
// Driver code
int main()
{
  // The Hex string that is to
  // be converted
  char *str = "4AF1";
   
  // Calling the function stoi
  // Storing the return value in
  // an unsigned integer
  signed number = stoi(str, 0, 16);
   
  // Displaying the unsigned integer
  // equivalent to the hex
  cout << "hex: " << str <<
          "\tinteger: " << number;
  return 0;
}


Output

hex: 4AF1    integer: 19185

Explanation: Firstly, the relevant header files were included. Then a string is defined containing the hex 4AF1 as value. This string (character array) is passed to the stoi function along with 0 and 16 as arguments. Where 0 is the default value of the size, and 16 is for hexadecimal conversion. The return value of the function is stored in a signed integer. This Hex string, along with its signed integer equivalent, is later displayed.

Convert Hex String to Signed Integer in C++

This article discusses converting a hex string to a signed integer in C++. There are 5 ways to do this in C++:

  1. Using stoi() function.
  2. Using stoul() function.
  3. Using sscanf() function.
  4. Using stringstream method.
  5. Using boost:lexical_cast.

Similar Reads

1. Using stoi function

stoi is a function in the string header file. The function takes as an argument a string and returns the converted integer. The function syntax is as follows:...

2. Using stoul function

...

3. Using sscanf function

The same effect could be produced using the stoul function in the bits/stdc++.h header file....

4. Using stringstream method

...

5. Using boost:lexical_cast

The same effect could be produced using the sscanf function in the default C++ distribution....