0

I recently had a bug converting a decimal string, e.g. "10.057", to a double. The issue was with the global application locale, the use of boost::lexical_cast and the fact that some European locales use a , for the decimal point.

scanf, printf and other functions within this family have the same issue.

I am interested to hear how others deal with this problem.

Jamerson
  • 474
  • 3
  • 14

1 Answers1

0

The behaviour of scanf, printf, boost::lexical_cast and related functions are dependent on the global application locale. They are therefore non-deterministic with respect to their input parameters. I have seen code like:

std::setlocale(LC_ALL, "C");
scanf(...);

However, this is not guaranteed to work in a multi-threaded environment.

A solution is to use functions and types that allow the user to explicitly specify the locale.

iostream stream objects allow the user to specify the locale as a parameter, and this will yield deterministic results.

std::istringstream istr("10.057");
istr.imbue(std::locale::classic());

double val;
istr >> val;

Similarly, boost::format allows the user to specify a locale as a parameter.

using boost::format;
std::string s = str(format("%lf", std::locale::classic()) % 10.057);

See also the discussion from a previous stackoverflow question.

Community
  • 1
  • 1
Jamerson
  • 474
  • 3
  • 14