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; } |
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++:
- Using stoi() function.
- Using stoul() function.
- Using sscanf() function.
- Using stringstream method.
- Using boost:lexical_cast.