1

I've got this weird behavior with std::atof in Ubuntu 18.0.4 with Qt Creator(4.10) as IDE / gcc 7.4.0 :

It parses strings as normal when i run in debug mode from QtCreator. But it floors when i run normally.

Example code with this behavior:

std::string exampleStr = "3.0303";
std::cout << "string value: " << exampleStr << std::endl;
std::cout << "double value - c_str(): " << std::atof(exampleStr.c_str()) << std::endl;

Output with normal run from IDE:

string value: 3.0303

double value - c_str(): 3

Output with running directly from executable:

string value: 3.0303

double value - c_str(): 3

Output with debug mode:

string value: 3.0303

double value - c_str(): 3.0303

I've tried both std::stof and std::strtof. Both same. Anybody knows the reason or work around of this bug?

Edit: I've workaround with this, but still wonder the reason of this behavior.

std::string exampleStr = "3.0303";    
std::stringstream ss;
ss << exampleStr;
float val = 0;
ss >> val;
std::cout << "Float value: " << val << std::endl;
Community
  • 1
  • 1
hsyntsy
  • 21
  • 4
  • 7
    This can happen e.g. when the locale (considered by `atof()`) isn't English or C but e.g. German. In German locale, instead of the decimal point, a comma (`,`) is considered to separate integral and fractional part of strings with floating points. (I once struggled myself with this and found it worth to mention.) FYI: [std::setlocale()](https://en.cppreference.com/w/cpp/locale/setlocale) – Scheff's Cat Mar 04 '20 at 12:49
  • Please show a complete [repro] that can be copy-pasted, compiled and run to reproduce the problem. Also please add whether you (might) use a locale in which the decimal-point character is not `.`, e.g. German, as explained above. – walnut Mar 04 '20 at 13:01
  • 1
    Qt creator is probably setting different environment variables which is changing the default locale – Alan Birtles Mar 04 '20 at 13:02

1 Answers1

1

I've changed locale with this:

std::setlocale(LC_ALL, "en_US.UTF-8");

and it worked for both debug and run modes. It's still interesting running in debug mode gets different locale than running normally. Thx for all responses.

hsyntsy
  • 21
  • 4