将数字转换为字符串的安全/可移植方式是什么(反之亦然)?
我在Linux上,我的设置区域设置是这样的,当我使用sprintf时,数字有","而不是"." 作为分隔符.
有时我想要那样,有时候不是:)
我看到了一些暗示玩用户设置的解决方案.显然,这是不应该做的事情.有人建议使用uselocale
可以有人详细说明(看起来它在一些glibc(<2.12)上有问题)并且如果可能的话提供一些示例代码(例如宏SNPRINTF_POSIX).
我试过自己,但我的C技能非常有限.
[编辑]
在写完我的问题后,我在Swisslinux.org上找到了[GO] Skywalker13的代码.有什么想法吗?内存使用情况怎么样?(我需要多次调用此函数)
#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;
}
Run Code Online (Sandbox Code Playgroud) 根据 TNTFreaks说明更新更新.
我有一个char变量数据定义如下:
#define CMD_LEN 4
char data[CMD_LEN + 1];
float n1;
# I pass the data variable to `serial_read` function
n = serial_read(serial_fd, data, CMD_LEN, TIMEOUT);
# Here, the process goes to serial_read function more below and
# after it return here again to follow ...
std::cout << "Data brought from serial_read method " << data << std::endl;
flush = tcflush(serial_fd, TCIOFLUSH);
//n = n*0.01f;
cout << "Applying sscanf " << std::endl;
sscanf(data, "%f", &n1);
printf("%.3f" …Run Code Online (Sandbox Code Playgroud)