I use the cerr stream to output my error, but I also wanted to store any of these errors in a string stream in memory.
I want to include this:
stringstream errorString; cerr << " Something went wrong "; errorString << " Something went wrong ";
AT
myErr << " Something went wrong ";
Where myErr is an instance of a class that stores this in a string stream and also outputs to cerr.
Thanks for any help.
You can create your class type myErras follows:
myErr
class stream_fork { std::ostream& _a; std::ostream& _b; public: stream_fork( std::ostream& a, std::ostream& b) : _a( a ), _b( b ) { } template<typename T> stream_fork& operator<<( const T& obj ) { _a << obj; _b << obj; return *this; } // This lets std::endl work, too! stream_fork& operator<<( std::ostream& manip_func( std::ostream& ) ) { _a << manip_func; _b << manip_func; return *this; } };
Using:
stream_fork myErr( std::cerr, errorString ); myErr << "Error Message" << std::endl;
You can use Boost.IOStreams .
#include <boost/iostreams/tee.hpp> #include <boost/iostreams/stream.hpp> #include <iostream> #include <sstream> namespace io = boost::iostreams; int main() { std::stringstream ss; io::tee_device<decltype(ss), decltype(std::cerr)> sink(ss, std::cerr); io::stream<decltype(sink)> stream(sink); stream << "foo" << std::endl; std::cout << ss.str().length() << std::endl; return 0; }
operator<< MyErr
operator<<
MyErr
MyErr& operator<< ( MyErr& myErr, std::string message) { cerr << message; errorString << message; //Where errorString is a member of the MyErr class return myErr; }
, :
int main() { MyErr myErr; myErr << " Something went wrong. "; return 0; }
, MyErr , , errorString, .
errorString
Boost tee.
tee
You need to subclass streambufand declare myErras ostreamwhich uses your subclass. Make the input functions do nothing, and then execute the output functions for any threads that you need.
streambuf
ostream
I had a class that did something similar 12 years ago, but lost it. I could not find a good example, but the docs for streambuf could be the starting point. Focus on protected output functions.