0

My problem is the following. I try to convert a string into double. In this way:

string str = "1.1";
double d = atof(str.c_str());

But this don't work, it simply return 1;

But if I try:

string str = "1,1";
double d = atof(str.c_str());

it return 1.1.

That is really weird. Seems it can only understand the number if I write a "," but return as a ".".

Any idea how could I solve this to convert "1.1" as well?

Gaboros
  • 191
  • 2
  • 14

1 Answers1

7

The function is locale aware, so it will parse the number according to your current locale settings.

Since atof is part of C library, you have to use C library to change the settings. Check out clocale.

Also have a look at C++ locale, which should be used if you use C++ features (string, istringstream) to parse the data. You can imbue the locale to the stream so that you don't modify the global locale as in the case of C.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • Thanks, that is the answer for my question! But do you have any idea how to set it than to use my current local settings but read 1.1? Because as you said, if I remove my locale setting it is work but I can't use letters of my own language. :( – Gaboros Jun 22 '12 at 11:36
  • @Gaboros: I only know the fact that it is locale-dependent. I cannot give any concrete example of how to modify the locale settings. I have edited my post to give some pointer on where to look. Hope that helps a bit. – nhahtdh Jun 22 '12 at 11:46
  • I found the asnwer! Thank you, you are great! :) I write down here if someone want to learn from it: Previously I used: setlocale(LC_ALL,"Hun"); which changed everything, include the number reading in it. So I have to use: setlocale(LC_CTYPE,"Hun"); which only change the letters of the locale, so numbers can be read as "1.1" instead of "1,1" and I can use my native language's letters. Thank you! – Gaboros Jun 22 '12 at 11:49
  • 1
    If you use `istream`, you can set a stream specific local. – James Kanze Jun 22 '12 at 11:59