How to use sscanf function In C++

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

Syntax:

int sscanf(const char *str, const char *format, ...)

Here,

str: This is the C string that the function processes as its source to retrieve the data.
format: This is the C string that contains one or more of the following items: Whitespace character, Non-whitespace character and Format specifiers

Example:

C++




// C++ program to implement the
// sscanf() function to convert
// a hex string to a signed integer
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
  // Hexadecimal String
  char char_string[] = "4F";
   
  // Initializing the unsigned
  // int to 0 value
  unsigned result = 0;
   
  // Calling the function and storing
  // the resultant value in the address
  // of result variable
  sscanf(char_string, "%X", &result);
   
  cout << result;
  return 0;
}


Output

79

Explanation: The string is initialized, containing the value 4F (int = 79). Another variable of unsigned int datatype is initialized with value 0. The sscanf function is called, and the string, along with hexadecimal format specifier “%X” and the integer that stores the resultant value, are passed as an argument. In the end, the value of the signed integer is 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....