Converting a string stream to a std::string
in C++ is straightforward using the str()
method. The str()
method of a string stream returns the underlying string that the stream has been writing to. Here’s how you can do it:
#include <iostream>
#include <sstream>
int main() {
std::ostringstream Stream;
Stream << "Hello, world!";
std::string Result = Stream.str();
std::cout << "Result: " << Result;
}
Result: Hello, world!
str()
MethodThe str()
method is a member function of std::ostringstream
, std::istringstream
, and std::stringstream
. When called without arguments, it returns the content of the stream as a std::string
.
Here’s a practical example where you might use a string stream to build a string and then convert it to a std::string
:
#include <iostream>
#include <sstream>
#include <string>
std::string FormatMessage(
const std::string& Name, int Age
) {
std::ostringstream Stream;
Stream << "Name: " << Name
<< ", Age: " << Age;
return Stream.str();
}
int main() {
std::string Message =
FormatMessage("Alice", 30);
std::cout << Message;
}
Name: Alice, Age: 30
In this example, we use a string stream to format a message. The FormatMessage()
function constructs the message using the <<
operator and then converts the stream to a std::string
using the str()
 method.
Remember, if you need to reuse the stream for new content, you should clear it:
Stream.str("");
Stream.clear();
This ensures the stream is empty and in a good state for further use.
In summary, converting a string stream to a std::string
is simple and useful for many common programming tasks, such as formatting output or constructing complex strings from various data types.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to C++ String Streams using std::stringstream
. Covers basic use cases, stream position seeking, and open modes.