Reputation: 35580
I'm looking to replace some snprintf calls with stringstreams. I need to ensure the output is identical.
given long l = some_input_var;
do
std::ostringstream str;
str << l;
return str.str();
and
buf str[24];
snprintf(str, 24, "%ld", l);
return std::string(str);
return identical strings?
What about for int
and "%d"
or double
and "%f"
?
Upvotes: 2
Views: 796
Reputation: 153977
In the standard, the C++ formatting is defined in terms of printf format
specifiers, so you can be pretty sure that simple formatters will work
the same. There are, however, things the iostream doesn't support (and
vice versa): there's no iostream equivalent of "% d"
, for example, and
the precision specification is ignored when outputting a string
(probably because iostream doesn't know whether the string would be part
of the format string, or correspond to a "%s"
).
Also, don't forget that all of the format options except width are sticky; you should save them, and restore them when you've formatted the element which needs them.
Upvotes: 1
Reputation: 477338
Yes. But it's a long story: iostreams formatting works via the stream's codec's formatting facet. The details are fairly involved; see C++11 27.7. The default facet's conversion uses sprintf
for input formatting and the strtoull
-type functions for output; see 22.4.2.1 for details.
Also and similarly, the new <string>
conversion functions std::to_string
use the default sprintf
format, and the various std::stoul
-like functions use the C library's strtoul
-like functions.
Upvotes: 2
Reputation: 5999
Let say that for that case the answer is yes, I wouldn't trust it to be the same for all cases, especially with the pains of making all the alignments right.
Did you consider Boost::format?
Something like return boost::str(boost::format("%ld") % l);
should work
and will provide for an easier migration path. Though differences do exist.
Upvotes: 0