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" ?
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
sprintffor input formatting and thestrtoull-type functions for output; see 22.4.2.1 for details.Also and similarly, the new
<string>conversion functionsstd::to_stringuse the defaultsprintfformat, and the variousstd::stoul-like functions use the C library’sstrtoul-like functions.