C: What is the portable/safe(thread aware) way to

2019-06-22 07:30发布

What is the safe/portable way to convert a number to a string (and the other way around) ?

I'm on Linux and my settings locale is so that when I use sprintf numbers have a "," instead of a "." as a separator.

Sometimes I want them that way, Sometimes not :)

I saw some solutions that imply playing with users settings. Clearly that's something one should not do. Somebody suggested using uselocale

snprintf : simple way to force . as radix?

can someone elaborate a bit (looks like it's buggy on some glibc (<2.12)) and if possible provide some sample code (eg a macro SNPRINTF_POSIX).

I tried myself but my C skills are very limited.

[edit]

I find this code by [GO]Skywalker13 on Swisslinux.org after writing my question. Any thoughts about it ? What about memory usage ? (I need to make numerous calls to this func)

#define _GNU_SOURCE
#include <locale.h>
#include <stdlib.h>

double
my_atof (const char *nptr)
{
  double res;
  locale_t new_locale;

  new_locale = newlocale (LC_NUMERIC_MASK, "C", NULL);
  res = strtod_l (nptr, NULL, new_locale);
  freelocale (new_locale);

  return res;
} 

标签: c locale glibc
1条回答
放我归山
2楼-- · 2019-06-22 08:34

With POSIX 2008, you can use the newlocale and uselocale functions to temporarily change the locale in the current thread without affecting other threads. This is really the only solution, aside from never setting the LC_NUMERIC locale category to begin with. On the other hand, I prefer banning use of LC_NUMERIC in software I write, at least for the global locale. Then you can use newlocale and uselocale locally at the point where you want numeric formatting that matches your user's cultural conventions, and on systems that lack POSIX 2008 uselocale, simply leave out localized numeric printing.

查看更多
登录 后发表回答