Redirect both cout and stdout to a string in C++ for Unit Testing

std::stringstream may be what you’re looking for.

UPDATE
Alright, this is a bit of hack, but maybe you could do this to grab the printf output:

char huge_string_buf[MASSIVE_SIZE];
freopen("NUL", "a", stdout);
setbuf(stdout, huge_string_buffer);

Note you should use “/dev/null” for linux instead of “NUL”. That will rapidly start to fill up huge_string_buffer. If you want to be able to continue redirecting output after the buffer is full you’ll have to call fflush(), otherwise it will throw an error. See std::setbuf for more info.

Leave a Comment