How to redirect an ostream object to a temporary buffer?

I have C ++ code that has many functions that receive ostream as an argument. I wanted to unit test those functions, for this I need to check the data of the ostream object after the function is executed. I can redirect the output stream to a file, but I wanted to check if I can create a temporary buffer and redirect the output stream to the buffer and read from this buffer.

+6
source share
1 answer

You can use std::stringstream as in std::ostream :

 #include <iosfwd> #include <sstream> #include <cassert> void my_func(std::ostream& out) { out << "test"; } int main() { std::ostringstream buf; my_func(buf); assert(buf.str() == "test"); } 
+15
source

Source: https://habr.com/ru/post/896077/


All Articles