简体   繁体   English

为什么printf系列函数关心语言环境?

[英]Why does the printf family of functions care about locale?

In iOS, if I use vswprintf with a non-western locale, it will fail and return -1. 在iOS中,如果我将vswprintf与非西方语言环境一起使用,它将失败并返回-1。

However, if I set the locale correctly it will write properly. 但是,如果我正确设置了语言环境,它将正确写入。

Why is this? 为什么是这样? Any ideas? 有任何想法吗?

Strangely, the implementation of vswprintf on iOS converts the wide string arguments it's given to narrow strings and then converts the result back to a wide string (I had to debug this issue once). 奇怪的是,iOS上vswprintf的实现将它给出的宽字符串参数转换为窄字符串,然后将结果转换回宽字符串(我不得不调试此问题一次)。 If your wide strings contain non-ASCII characters in them, then this is a lossy conversion, and only certain characters can be successfully converted. 如果您的宽字符串中包含非ASCII字符,那么这是一个有损转换,只能成功转换某些字符。

The exact set of non-ASCII characters which can be converted depends on the current locale setting. 可以转换的确切非ASCII字符集取决于当前的语言环境设置。 If you try to pass in unsupported characters, then vswprintf will fail by returning -1 and setting errno to the error EILSEQ (illegal multibyte sequence). 如果您尝试传入不受支持的字符,则vswprintf将失败,返回-1并将errno为错误EILSEQ (非法多字节序列)。

On Mac OS X, at least, you can get around this by switching to a UTF-8 locale, eg: 至少在Mac OS X上,您可以通过切换到UTF-8语言环境来解决这个问题,例如:

setlocale(LC_CTYPE, "UTF-8")

However, this doesn't appear to work on iOS, so if you need to be able to vswprintf all characters without knowing the locale in advance, I'm afraid you're out of luck unless you reimplement vswprintf yourself. 但是,这似乎不适用于iOS,所以如果你需要能够在不事先知道语言环境的情况下vswprintf所有角色,我恐怕你运气不好,除非你自己重新实现vswprintf

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

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