×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Convert hex string to integer using stoi() function in C++ STL

C++ STL stoi() function: Here, we are going to learn how to convert a given hexadecimal string to an integer using stoi() function.
Submitted by IncludeHelp, on March 11, 2019

Problem statement

Given a hex string, we have to convert it into an integer using stoi() function.

C++ STL stoi() function

stoi() stands for string to integer, it is a standard library function in C++ STL, it is used to convert a given string in various formats (like binary, octal, hex or a simple number in string formatted) into an integer.

Syntax

int stoi (const string&  str, [size_t* idx], [int base]);

Parameters

  • const string& str is an input string.
  • size_t* idx is an optional parameter (pointer to the object whose value is set by the function), it's default value is 0 or we can assign it to nullptr.
  • int base is also an optional parameter, its default is 10. It specifies the radix to determine the value type of input string (2 for binary, 8 for octal, 10 for decimal and 16 for hexadecimal).

Return value

It returns converted integer value.

Here is an example with sample input and output:

Input:
string hex_string = "1F1FA2";

Function call:
stoi(hex_string, 0, 16);

Output:
2039714

C++ STL code to convert a hex string into an integer

#include <iostream>
#include <string>
using namespace std;

int main() {
  string hex_string = "1F1FA2";
  int number = 0;

  number = stoi(hex_string, 0, 16);
  cout << "hex_string: " << hex_string << endl;
  cout << "number: " << number << endl;

  hex_string = "12345";
  number = stoi(hex_string, 0, 16);
  cout << "hex_string: " << hex_string << endl;
  cout << "number: " << number << endl;

  return 0;
}

Output

hex_string: 1F1FA2
number: 2039714
hex_string: 12345
number: 74565

Reference: std::stoi()

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.