0

I have written a program in C++ in Linux (Ubuntu 12.04) platform which print my required output into the stdout in every second. It means, after 10 seconds, I have 100 lines (each stdout in every second is 2 lines report) in the stdout.

This is my applied simulation format and i cannot change any variable or method to write the output into the variable instead of the stdout.

I am going to save this output into the string variable instead of the stdout. How is it possible by C++ language?

BlueBit
  • 397
  • 6
  • 22
  • When you say "stdout" do you mean you tse `printf()` or `fprintf(stdout, ...)`? In that case I don't think there is a solution. If you mean `std::cout` there is a solution. – Dietmar Kühl Sep 28 '13 at 12:22

1 Answers1

1

You can use a string stream for that. Suppose your original logging function is like this:

void log(std::ostream & o, std::string msg)
{
    o << msg << std::endl;
}

int main()
{
    // ...
    log(std::cout, "Ping");
}

Change this to:

#include <sstream>

int main()
{
    std::ostringstream oss;

    // ...
    log(oss, "Ping");
}

If that's not an option, you can mangle the global std::cout's output buffer:

std::streambuf * sbuf = std::cout.rdbuf();   // save original

std::ostringstream oss;
std::cout.rdbuf(oss.rdbuf());                // redirect to "oss"

// ...

std::cout.rdbuf(sbuf);                       // restore original

In either case, oss.str() contains the string data.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • How can i band the stdout printing by the default program and allow to print my own string variable (oss.str()) with my format in the stdout? – BlueBit Sep 28 '13 at 12:02
  • @BlueBit: Sorry, I don't understand your question. What do you want to format? – Kerrek SB Sep 28 '13 at 12:08
  • I mean, i do not want to my default stdout in my program be printed. Just copy the stdout into the string variable. How can i band the printing stdout? Is it clear, friend? :-) – BlueBit Sep 28 '13 at 12:11
  • @BlueBit: The last part with changing `rdbuf` should accomplish that. Give it a try, and see also the answer I linked in the "duplicate" comment above. – Kerrek SB Sep 28 '13 at 12:15
  • What does "Ping" mean? I should replace "Ping" with std::cout? because you mention: log(oss, "Ping"); It just send "Ping" to stdout. Yes? – BlueBit Sep 28 '13 at 13:21