How to use C++ STL sscanf() function In C++

sscanf function is basically used to read the data from a string buffer.

Syntax:

int sscanf( const char* buffer, const char* format,….);

Here the buffer is a pointer to a null-terminated character string to read the data and the format pointer to a null-terminated character string specifies how to read the data, and lastly, we will add one more parameter to where to store the value.

Below is the C++ program to convert a hex string to an integer using sscanf() function:

C++




// C++ program to convert a hex
// string to an integer using
// sscanf() function
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
  string s = "DD";
  int ans;
   
  // Converting a hexadecimal C-string
  // to an integer using the format %x
  // and storing it into ans variable
  sscanf(s.c_str(), "%x", &ans);
  cout << ans << endl;
  return 0;
}


Output

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++:

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

Let’s start discussing each of these methods in detail.

Similar Reads

1. Using C++ STL stoi() function

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 header file. It contains three parameters:...

2. Using C++ STL sscanf() function

...

3. Using C++ STL stoul() function

sscanf function is basically used to read the data from a string buffer....

4. Using C++ STL string stream method

...

5. Using C++ STL boost:lexical_cast function

This is an STL function in C++11 that is defined in the header file , which is also used to convert a string to an integer....