Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect ostream object to a temporary buffer?

I have a C++ code that has a lot of functions which receives ostream as argument. I wanted to unit test those functions, for that I have to verify ostream object data after execution to the function. I can redirect 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 that buffer.

like image 618
sarbojit Avatar asked Aug 28 '11 14:08

sarbojit


1 Answers

You can use std::stringstream as an in memory 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");
}
like image 157
Flexo Avatar answered Sep 23 '22 07:09

Flexo