简体   繁体   English

如何消除同一程序的gui和命令行界面之间的语言环境差异?

[英]How do I remove the difference in locale between gui and commandline interfaces of same program?

The program saves a settings file as text which contains floating point numbers of type long double . 该程序将设置文件另存为文本,其中包含long double类型的浮点数。 The settings file can only be saved via the GUI (GTK2), while files can also be loaded via the command line and without bringing up the GUI. 设置文件只能通过GUI(GTK2)保存,而文件也可以通过命令行加载而无需打开GUI。

Unfortunately, a user reports that in the files he has saved, due to his locale setting, the numbers are formatted with commas and the program refuses to load them (emitting error messages) from the command line but seems to load them when the GUI is open. 不幸的是,用户报告说,由于其语言环境设置,在他保存的文件中,数字使用逗号格式化,并且程序拒绝从命令行加载它们(发出错误消息),但是似乎在GUI加载时加载它们。打开。

I have already asked the following question: MPFR, printf, decimal places, locales, file i/o problem which suggested using setlocale(LC_ALL, "C") which I placed at the beginning of main . 我已经问过以下问题: MPFR,printf,小数位,语言环境,文件I / O问题 ,建议使用setlocale(LC_ALL, "C")放置在main的开头。 As this did not work, I placed it after calling gtk_init_check but again, it made no difference. 由于这不起作用,因此我在调用gtk_init_check之后放置了它,但再次没有区别。 ( EDIT It did make a difference after I installed a few locales.) 编辑在安装一些语言环境后确实有所不同。)

I want the program to always use the same locale setting (or non-localized locale setting - "C") for these data files it saves, but don't want to mess up the GUI by doing so. 我希望程序对它保存的这些数据文件始终使用相同的语言环境设置(或非本地化的语言环境设置-“ C”),但不想这样做,从而弄乱了GUI。

How? 怎么样?

do not use locale sensitive functions for save and restore values at all. 完全不使用对语言环境敏感的功能来保存和恢复值。 For example use ieee754.h for save and loading mantissa and exponent. 例如,使用ieee754.h保存和加载尾数和指数。

If you can live with only storing these values as double , I would simply suggest using glib's ASCII-limited string formatting/parsing functions: 如果您只能将这些值存储为double ,那么我只建议使用glib的ASCII限制的字符串格式/解析函数:

To convert a value to string, call g_ascii_dtostr() . 要将值转换为字符串,请调用g_ascii_dtostr() To go the other way, use g_ascii_strtod() . g_ascii_strtod() ,请使用g_ascii_strtod()

I realize this might be bad since you drop precision going from long double to plain old (g)double , of course. 我意识到这可能是不好的,因为您当然会将精度从long double到普通旧(g)double It doesn't seem glib supports a long double type, are you sure it really gives you more precision? 似乎glib不支持long double精度类型,您确定它确实可以提高精度吗?

Store the locale in use at the top of your load/save code: 将正在使用的语言环境存储在加载/保存代码的顶部:

char* loc = setlocale(LC_NUMERIC, NULL);

Then for every instance where you write numeric values to your file call: 然后,对于将数字值写入文件调用的每个实例:

setlocale(LC_NUMERIC, "C");
/* code here for read/write of numeric values:
fprintf(fd, "aspect %0.20lf\n", img->aspect);
*/
setlocale(LC_NUMERIC, loc);

Should do the trick. 应该做到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM