C++ String Streams: Creating and Using std::stringstream
To create a string stream in C++ using the STL (Standard Template Library), you can use the 'std::stringstream' class. Here's an example:
#include <iostream>
#include <sstream>
int main() {
// Create a string stream object
std::stringstream ss;
// Write data to the string stream
ss << 'Hello, ';
ss << 'World!';
// Read data from the string stream
std::string result = ss.str();
// Print the result
std::cout << result << std::endl;
return 0;
}
In this example, we first include the necessary headers '
We can write data to the string stream using the '<<' operator, just like we would with 'std::cout'. In this case, we write the string 'Hello, ' and 'World!' to the stream using multiple '<<' operations.
To read data from the string stream, we use the 'str()' member function to get the contents of the stream as a 'std::string'. We store the result in the 'result' variable.
Finally, we print the result using 'std::cout'. The output will be 'Hello, World!'.
Note that 'std::stringstream' provides similar functionality to 'std::istringstream' and 'std::ostringstream', which are used for input and output respectively.
原文地址: https://www.cveoy.top/t/topic/o7dZ 著作权归作者所有。请勿转载和采集!