【发布时间】:2015-01-05 03:33:18
【问题描述】:
考虑这个示例程序:
#include <cstdio>
#include <cwchar>
#include <string>
int main()
{
std::string narrowstr = "narrow";
std::wstring widestr = L"wide";
printf("1 %s \n", narrowstr.c_str());
printf("2 %ls \n", widestr.c_str());
wprintf(L"3 %s \n", narrowstr.c_str());
wprintf(L"4 %ls \n", widestr.c_str());
return 0;
}
这个的输出是:
1 narrow
2 wide
我想知道:
- 为什么不打印 3 和 4?
- 1 & 3 和 2 & 4 有什么区别?
-
narrowstr是 UTF8 和widestr是 UTF16 有什么区别吗?
【问题讨论】:
-
"widestr is in utf16" 表示您使用的是 Windows(更多 Unicode 友好的系统使用 UTF-32 作为宽字符串的默认值)。如果您想在使用标准 C++ 或 C 的 WIndows 系统上执行 ASCII 以外的任何操作,则有许多神秘的箍要跳。您不妨放弃并使用 WinAPI。
-
不要屈服于微软的愚蠢行为。省去自己的痛苦,编写自己的字符串库。看在上帝的份上,不要使用 windows 宏转换和其他疯狂的东西,相信我,这太可怕了,而且在混乱中会出现各种错误。
-
#4 可能没有打印,因为您的程序在 #3 上崩溃了。
%ls是最便携的打印wchar_t字符串的方法,可以同时使用printf和wprintf。您应该避免使用%S,因为它的 Visual C++ 解释与 C99/C++11 标准完全相反。
标签: c++ unicode printf widechar