Nick Forrington said:
Hi, I'm making a program and have a static Console class that I'm using to
output things, these get sent to the console and also to the graphics on
screen (I'm using SDL). One thing I'm having a bit of trouble with is
passing strings and numbers in the same arguement
e.g.
Console:
rintln("X=" + x);
kind of thing?
anyone suggest a good solution? the only way I can seem to do it now is by
creating a string and doing something like
string s = "X=";
s += x;
This obviously gets more messy, but I'll have to stick with it if noone
has a better idea.
First of all, the C++ standard library already has built-in output
streams for writing debugging information: cerr, clog, or even cout.
These outputs can be redirected to a file or a console window using
OS facilities.
In your program, you can also replace the 'stream buffer' behind any
of these logging outputs, and transmit the data to the destination of
your choice. ( using the rdbuf() method)
See this example for redirection to a file:
http://groups.google.com/[email protected]
For other output destinations, you need to implement a custom subclass
of std::stream_buf. Dietmar Kühl, an expert on this topic, has a couple
examples available on his website: (see GUI window)
http://www.informatik.uni-konstanz.de/~kuehl/
Of course you don't *have* to reuse cout, you can also create another
ostream instance for your custom streambuf.
If you only want to generate formatted strings and use 'println' as above,
I would recomment taking a look at the excellent, free, peer_reviewed
boost::format library:
http://www.boost.org/libs/format/index.html
This is a safe and flexible solution.
It might well be the best/easiest option for what you are wanting to do.
Take also a look at boost's lexical_cast, a 2-way superset of Victor's
"toString":
http://www.boost.org/libs/conversion/lexical_cast.htm
I will also mention two tricks that can be used, but which I
cannot recommend for any serious development:
You could use a macro hack to use stringstream on the fly.
Something like:
#include <sstream>
#define TO_STRING( output ) \
static_cast<std:
stringstream&>( \
std:
stringstream() << "" << output \
).str().c_str();
You can then write:
Console:
rintln(TO_STRING( "pi is" << 3.1416 << " !");
Another alternative is to emulate the sprintf interface using a function
that in turn calls vsprintf to convert the string, then outputs it.
This however tends to be bug-prone (you need to use non-standard library
functions to guarantee no buffer overflow, and this has all the other
caveats of std:
rintf).
I hope this helps, let me know of the approach you'll choose
Ivan