snprintf:简单的强制方法。作为基数?
我的程序在一台机器上运行不正确,所以我开始寻找错误,我发现在那台机器上,snprintf 使用逗号 (,),而不是 . (点)与 99% 的其他计算机一样(至少根据我的经验)。
这不应该标准化吗?
我正在使用一个假设基数为 的库。 (点),因此它不能与逗号一起正常工作。
所以我的问题是,有没有一种简单的方法来强制点作为基数字符?我知道我可以搜索&手动用点替换逗号,但肯定有更干净的方法。
My program was not behaving correctly on one machine so I started to hunt for the bug, and I discovered that on that machine, snprintf uses a comma (,), not a . (dot) as 99% of other computers (at least in my experience).
Shouldn't this be standardized?
I am using a library that assumes that the radix is a . (dot) and so it does not work properly with a comma.
So my question is, is there a simple way to force the dot as the radix character? I know I could just search & replace the comma by a dot manually, but surely there is a cleaner way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该能够使用 setlocale 函数更改区域设置,以使 snprintf 使用点。尝试将其设置为“POSIX”或“C”。 (
setlocale(LC_ALL, "POSIX")
You should be able to change your locale-setting using the
setlocale
-function to make snprintf use a dot. Try setting it to "POSIX" or "C". (setlocale(LC_ALL, "POSIX")
.
与,
由区域设置的LC_NUMERIC
部分设置。因此,请确保将程序设置为使用.
的区域设置(例如"POSIX"
)。.
versus,
is set by theLC_NUMERIC
part of the locale. So make sure you set your program to use a locale that uses the.
(such as"POSIX"
).对于库代码,您可能希望使用 POSIX 2008
uselocale
函数而不是setlocale
。它能够设置特定于线程的区域设置,因此,如果从使用线程的程序调用您的库代码,它不会扰乱其他线程的行为(和/或使程序崩溃,因为setlocale
不是线程安全的)。对于应用程序代码,您应该避免将
LC_NUMERIC
语言环境类别设置为除 C/POSIX 之外的任何内容。对于大多数应用程序,您真正需要设置的唯一类别是LC_CTYPE
、LC_MESSAGES
和可能的LC_COLLATE
。For library code, you may wish to use the POSIX 2008
uselocale
function instead ofsetlocale
. It is able to set a thread-specific locale, so that if your library code is called from a program that uses threads, it won't mess up the other threads' behavior (and/or crash the program, sincesetlocale
is not thread-safe).For application code, you should simply avoid ever setting the
LC_NUMERIC
locale category to anything but C/POSIX. The only categories you really need to set for most applications areLC_CTYPE
,LC_MESSAGES
, and possiblyLC_COLLATE
.