2

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?

Craig Wright
  • 1,575
  • 1
  • 11
  • 19
  • Is 'none' a valid answer? And you might want to stick your `sprintf` vs `_snprintf` question under a C tag. – Xymostech Oct 31 '12 at 01:13
  • 2
    [Performance](http://stackoverflow.com/questions/445315/why-is-snprintf-faster-than-ostringstream-or-is-it) possibly but you would have to measure. – Jesse Good Oct 31 '12 at 01:14

2 Answers2

6

I use sprintf all 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 _snprintf if 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 sprintf or 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 copying string objects about.

Not saying that I don't use ostringstream -- I certainly do (although more often I use istringstream, going the other way)... But I prefer to have two tools at my disposal instead of one.

paddy
  • 60,864
  • 6
  • 61
  • 103
1

You would never prefer sprintf over streams, but you might consider snprintf (or _snprintf for MS compilers) in some circumstances.

For suitably performance-intensive pieces of code where performance has been measured, snprintf might give you a performance boost over using streams.

Additionally you might consider using snprintf if you're already maintaining a char[] buffer to pass into a C API.

And just to reiterate, you should always prefer _snprintf or snprintf over sprintf because they help prevent a wide variety of security issues and/or hard to find bugs.

Mark B
  • 95,107
  • 10
  • 109
  • 188