c++ - Swapping a stringstream for cout -


with glibc's stdio, can swap memstream stdout, thereby capturing output of piece of code compiled output stdout:

#include <stdio.h>  void swapfiles(file* f0, file* f1){ file tmp; tmp = *f0; *f0 = *f1; *f1 = tmp; }  void hw_c(){ puts("hello c world"); }  int c_capt(){   file* my_memstream;   char* buf  = null;   size_t bufsiz = 0;    if( (my_memstream = open_memstream(&buf, &bufsiz)) == null) return 1;    file * oldstdout = stdout;    swapfiles(stdout, my_memstream);   hw_c();   swapfiles(stdout, my_memstream);    fclose(my_memstream);   printf("captured: %s\n", buf); } 

i'm curious if same possible iostreams. naive attempt won't compile:

#include <iostream> #include <string> #include <sstream>  void hw_cc(){ std::cout<<"hello c++ world\n"; } int cc_capt(){   using namespace std;    stringstream ss;   string capt;    //std::swap(ss,cout); //<- compiler doesn't   hw_cc();   //std::swap(ss,cout);     cout<<"captured: "<<capt<<'\n'; }  int main(int argc, char** argv){   c_capt();   puts("---------------------------------");   cc_capt();   return 0; } 

you can, don't swap whole stream--just stream buffer.

void cc_capt() {     using namespace std;      stringstream ss;      auto orig = std::cout.rdbuf(ss.rdbuf());      hw_cc();      std::cout.rdbuf(orig);      std::cout << "captured: " << ss.str() << "\n"; } 

note in case, we're note using stringstream @ all, stringbuf contains. if wanted, define basic_stringbuf<char> , use directly instead of defining stringstream, use use stringbuf contains.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -