#include#include int main() { std::ofstream file("example.txt"); std::streambuf* backup = std::cout.rdbuf(); // Redirect cout to file std::cout.rdbuf(file.rdbuf()); // Output to file std::cout << "This is an example line." << std::endl; // Restore cout std::cout.rdbuf(backup); return 0; }
#includeIn this example, we create an `std::ostringstream` object named `stream`. We then use `stream.rdbuf()->sputn()` to write a string to the buffer. Finally, we extract the string from the buffer using `stream.str()` and output it to `std::cout`.#include int main() { std::ostringstream stream; stream.rdbuf()->sputn("This is an example line.", 24); std::string output = stream.str(); std::cout << output << std::endl; return 0; }