Skip to content

Instantly share code, notes, and snippets.

@tknopp
Created February 28, 2014 13:36
Show Gist options
  • Save tknopp/9271244 to your computer and use it in GitHub Desktop.
Save tknopp/9271244 to your computer and use it in GitHub Desktop.
Locale independent strtod
#if defined(_OS_WINDOWS_)
#include <stdlib.h>
#include <locale.h>
// Cache locale object
static int c_locale_initialized = 0;
static _locale_t c_locale;
_locale_t get_c_locale()
{
if(!c_locale_initialized)
{
c_locale_initialized = 1;
c_locale = _create_locale(LC_ALL,"C");
}
return c_locale;
}
double strtod_c(const char *nptr, char **endptr)
{
return _strtod_l(nptr, endptr, get_c_locale());
}
#else
#include <stdlib.h>
#include <xlocale.h>
// Cache locale object
static int c_locale_initialized = 0;
static locale_t c_locale;
locale_t get_c_locale()
{
if(!c_locale_initialized)
{
c_locale_initialized = 1;
c_locale = newlocale(LC_ALL_MASK, NULL, NULL);
}
return c_locale;
}
double strtod_c(const char *nptr, char **endptr)
{
return strtod_l(nptr, endptr, get_c_locale());
}
#endif
@pavel-perina
Copy link

Please change

   c_locale = newlocale(LC_ALL_MASK, NULL, NULL);

with

   c_locale = newlocale(LC_ALL_MASK, "C", NULL);

on line 39. Otherwise c_locale will be set to 0 and passing 0 to strtod_l will cause crash (at least in my glibc implementation).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment