How to use stringstream In C++
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input. The basic methods are:
- clear() – To clear the stream.
- str() – To get and set a string object whose content is present in the stream.
- operator <<- Add a string to the stringstream object.
- operator >>- Read something from the stringstream object.
Example:
C++
#include <bits/stdc++.h> using namespace std; int main() { float x=5.5; stringstream s; s<<x; // appending the float value to the streamclass string result=s.str(); //converting the float value to string cout << "Converted value from float to String using stringstream is : " <<result<<endl; return 0; } |
Output
Converted value from float to String using stringstream is : 5.5
Explanation: The stringstream class converts the float value from a variable to a string. It is an inbuilt class present in the C++ Library.
Convert Float to String In C++
In this article, we learn how we can convert float to string in C++ using different methods:
- Using the to_string()
- Using stringstream
- Using Macros
- Using lexical_cast from the boost library