getting cout output to a std::string

venkysmarty picture venkysmarty · Mar 4, 2011 · Viewed 56.3k times · Source

I have the following cout statement. I use char arrays because I have to pass to vsnprintf to convert variable argument list and store in Msg.

Is there any way we can get cout output to C++ std::string?

char Msg[100];
char appname1[100];
char appname2[100];
char appname3[100]; 

// I have some logic in function which some string is assigned to Msg.
std::cout << Msg << " "<< appname1 <<":"<< appname2 << ":" << appname3 << " " << "!" << getpid() <<" " << "~" << pthread_self() << endl;

Answer

Bj&#246;rn Pollex picture Björn Pollex · Mar 4, 2011

You can replace cout by a stringstream.

std::stringstream buffer;
buffer << "Text" << std::endl;

You can access the string using buffer.str().

To use stringstream you need to use the following libraries:

#include <string>  
#include <iostream> 
#include <sstream>