Re: std::to_string(int) deviates from iostreams result - deliberate?
On 2014-04-16 17:18, Martin Ba wrote:
I've noticed something interesting in the specification of
[std::to_string][1]:
It is defined in terms of std::sprintf and outputting a number with
sprintf is *not* the same as using `operator<<` on a stream.
Correct. The idea behind specifying the to_(w)string overloads was to
provide a convenience function to allow the creation of a simple string
representation for built-in types so that user-code is not required to
struggle with the C API or configuring a stream to that effect. It never
was intended to mimic the behaviour or even the formatting choices of IO
streams.
An [ostream][2] uses [std::numput][3] to output numbers, but numput uses
thousands grouping and [std::printf][4] does *not* use thousands grouping.
Right.
So, interestingly, the following two snippets will *not* produce the
same results:
#include <iostream>
#include <string>
void f() {
const int x = 10000;
std::cout << std::to_string(x); << '\n';
// => "10000"
}
void f() {
const int x = 10000;
std::cout << x << '\n';
// => may be "10.000" or "10,000" depending on global locale
}
Was this design choice deliberate?
Yes, it was. There was never the intention to ensure equal behaviour of
IO stream output and std::to_string result.
Would you think it is a problem?
I don't see such a problem. You should only use the to_string functions
if you do not depend on the effects of locales. If you do, you need a
more fine-grained API for such purposes to control the effects.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]