How to use stringstream method In C++

The stringstream method morphs the string object with a stream to make it seem like the data is being read from a stream. The library is primarily used for parsing data stored inside strings. 

Example:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    unsigned x;
   
      // Hexadecimal String
    string str = "FF";
 
    // Used for segregation of characters
    istringstream iss(str);
 
    // Converting to integer and storing the result in x
    iss >> hex >> x;
 
    cout << x;
}


Output:

255

Explanation: 

Alike the previous examples, an unsigned integer variable and a string containing the hexadecimal code are stored in separate variables. Then the string is passed as an argument to the iss function. The function converts the regular string to a stream. Then the base field format is set to hex, leading to the conversion of the hexadecimal string to integer, and the result is stored in the variable x. It is done by using a hex manipulator. In the end, the unsigned value 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....