atof considers locale under linux?
count

I recently tested my game under linux just to see that it doesn't work correctly.
I hunted the problem down to some float values being 0 which should not be.
All those values are converted to float from string using atof().

The problem now is that atof under linux seems to take the locale of my machine into account.

I'm on a german windows xp so normally float values are written like 0,5 not like 0.5.

This code works under windows:

char * c = "0.5";
float f = atof(c); // f = 0.5

But on linux it behaves like this:

char * c1 = "0.5";
char * c2 = "0,5";
float f1 = atof(c1); // f1 = 0
float f2 = atof(c2); // f2 = 0.5

What did I miss?
Why is there the behavior different? And how should I deal with this problem?
I'm very surprised that atof is locale aware! ???

Thomas Fjellstrom

It seems atof and strtod are locale dependant. You'll probably want to set the locale to C in your program.

setenv("LC_ALL", "C"); might be all you need. Or if you only want to change the numerics: setenv("LC_NUMERIC", "C");

editInf:

libc might not notice env vars in a running program, I don't know, if it doesn't try:

#include <locale.h>
setlocale(LC_NUMERIC, "C");

count

strtod behaves exactly the same.
So i will check out how to set the locale. Never did so with c++.
Did I understand you correctly that "C" is an own locale?

EDIT:
Missed your edit :)
Thanks for the infos! Will try that.

EDIT2:
But why is it different for windows and linux?

Thomas Fjellstrom

Did I understand you correctly that "C" is an own locale?

Yup. Its a simplified locale that libc uses when nothing else is set. Its also the default fairly often if you don't select one on install.

Quote:

But why is it different for windows and linux?

Probably because windows doesn't support "Locales".

count

Probably because windows doesn't support "Locales".

Ok. Sounds reasonable.

It is working now.
Thank you very much!
(Forgot to make this a cookie thread :-/)

X-G

Windows does support locales. We were bitten by this problem when some code that used sscanf() under MSVC stopped working mysteriously.

Thomas Fjellstrom
X-G said:

Windows does support locales.

Standard libc locale's? or its own notion?

count

How did you solve it?
Like Thomas suggested?

X-G

Standard libc locale's? or its own notion?

Standard libc locales, yes.

How did you solve it?

setlocale(LC_ALL, "C"); as a hack, fixed it properly by getting rid of sscanf (which is a horrid function anyway).

(EDIT, Protip: Under C++, you can imbue() an iostream with the locale you want.)

count
X-G said:

Protip: Under C++, you can imbue() an iostream with the locale you want.

Nice! That's pretty useful.

Thread #600366. Printed from Allegro.cc