0

I have a console application written with C++. Is there any way to collect all stdout output from it to string/pipe/memory array?

PS. I need to do this from within the console app that I'm needing to collect stdout from. Or, in other words, it is collecting from itself.

ahmd0
  • 16,633
  • 33
  • 137
  • 233
  • What have you done so far? – Mats Petersson Mar 14 '13 at 20:32
  • That doesn't make sense. If it's from within the app itself you already have the output, send it elsewhere. To answer the actual question, yes it's possible. Having an app that just logs stdout makes sense but I don't get where you're going with this. – evanmcdonnal Mar 14 '13 at 20:33
  • If file output is okay, you can use `freopen()` to do this. See http://stackoverflow.com/questions/5257509/freopen-equivalent-for-c-streams – jxh Mar 14 '13 at 20:41

1 Answers1

3

Yes. To redirect it to a string, you can use a std::stringstream

std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());

Then, if you do:

std::cout << "Example output" << std::endl;
std::string text = buffer.str();

You will see that text now contains "Example output\n".

meyumer
  • 5,063
  • 1
  • 17
  • 21
  • My output mostly comes from C-like calls to `_tprintf(_T("Some line1\n"));` that doesn't seem to be caught by your approach. Any idea why? – ahmd0 Mar 14 '13 at 21:09