Does anyone have any concrete examples with real reasons as to why one would prefer sprintf over stringstream in a C++ environment? Moreover, if you are working in the Microsoft world is there any reason to ever prefer sprintf to _snprintf?
Share
I use
sprintfall the time in C++. I find it easier to work with, particularly when I am writing timestamps and other specially-formatted strings. Sure, you can do this with stream modifiers, but it’s so long-winded, you can’t see what the code is achieving at a glance.It is preferable over
_snprintfif you absolutely know that you won’t be overflowing a buffer, and you require the fastest possible write or just don’t want the extra parameter clutter.Speaking of buffers, that’s the other thing… Usually I would use
sprintfor its variants when I have a buffer on the stack or I am writing into an existing buffer in memory. I wouldn’t necessarily want the overhead of allocating and copyingstringobjects about.Not saying that I don’t use
ostringstream— I certainly do (although more often I useistringstream, going the other way)… But I prefer to have two tools at my disposal instead of one.