@Matt, I'm with you. I've always hated streams. Sure, I can use them. Make them do pretty much anything I want. But I like printf
because I prefer the syntax.
I even wrote a strprintf
that worked exactly the same as sprintf
except returned a std::string
instead of writing to a char buffer.
But gradually, begrudgingly, I have almost completely stopped using sprintf
. Because, simply speaking, I write too damned many bugs and I get sick and tired of going over and over my same mistake time & time again. stringstream
s type safety saves me from myself.
The bugs I'm talking about for me come in 2 forms, mainly:
I picked the wrong magic number for my output buffer. Say I come up with char buf_[256]
to format up a little something. Well, just like Bill Gates famously attributed comment that "256KB of memory ought to be enough for anybody," I'm wrong on the low side enough to catch my eye. On the other hand, what am I going to do? char buf_[1024*64]
? Extreme, but you get the point. There's no perfect magic number. You either expose yourself to more crashes, or you waste memory.
I sprintf
-ed a string, but sent it a float. Do this all the time. Well, not all the time. For every 100 calls to sprintf
, I probably do this once or twice. For production code, that's a lot.
With streams neither of these can ever happen. So I use streams now, and my code never crashes. Well... there, anyway.
Some will say that streams are slower than sprintf. Eh, maybe. For the sake of argument, I'll even just go along with it. Doesn't matter much though. I work on real-time stock market servers that routinely process 3 million messages per second, all day long. And I've never had a problem with the speed of streams. Maybe it's a little slower, but I've got bigger fish to fry.