First step, Inherit Std::streambuf
#include <iostream> #include <streambuf>class mystreambuf:public std::streambuf{enum{buffer_size = 255,}; Public:mystreambuf () {buffer_[buffer_size] = ' buffer_ '; Setp (buffer_, buffer_size-1 +);} ~mystreambuf () {sync ();} Protected:virtual Int_type Overflow (int_type c) {if (c! = EOF) {*pptr () = C;pbump (1);} Flush_buffer (); return c;} virtual int sync () {flush_buffer (); return 0;} Private:int Flush_buffer () {int len = int (pptr ()-pbase ()); if (len <= 0) return 0;if (len <= buffer_size) Buffer_[len] = ' + '; #ifdef ANDROID android_logpriority t = android_log_info;__android_log_write (t, "MyLog", buffer_); #else printf ("%s", buffer_); #endif pbump (-len); return Len;} Private:char buffer_[buffer_size + 1];};
The second step is to create the Mystreambuf object and assign it to Std::cout
Mystreambuf g_mystreambuf;std::cout.rdbuf (&G_MYSTREAMBUF);//note:std::endl will immediately call the sync method to write the buffer character to log, not just line wrap with STD :: cout << "Hello" << 123 << std::endl;std::cout << "PI =" << 3.14 << Std::endl;
This allows the logcat of eclipse to view the std::cout output.
Android NDK redirect Std::cout output to log