Windows CMD不能正确输出UTF-16
Windows CMD not output UTF-16 correctly
我试图输出非ascii字符到Windows CMD,但问题是,它不工作。我没有写下面的代码,我把这两部分粘在一起。该代码应该将字符转换为UTF-8,然后从UTF-8转换为UTF-16,以便在Windows上正确显示。下面是代码:
// codecvt::in example
#include <iostream> // std::wcout, std::wcout
#include <locale> // std::locale, std::codecvt, std::use_facet
#include <string> // std::wstring
#include <cwchar> // std::mbstate_t
void GetUnicodeChar(unsigned int code, char chars[5]) {
if (code <= 0x7F) {
chars[0] = (code & 0x7F); chars[1] = ' ';
} else if (code <= 0x7FF) {
// one continuation byte
chars[1] = 0x80 | (code & 0x3F); code = (code >> 6);
chars[0] = 0xC0 | (code & 0x1F); chars[2] = ' ';
} else if (code <= 0xFFFF) {
// two continuation bytes
chars[2] = 0x80 | (code & 0x3F); code = (code >> 6);
chars[1] = 0x80 | (code & 0x3F); code = (code >> 6);
chars[0] = 0xE0 | (code & 0xF); chars[3] = ' ';
} else if (code <= 0x10FFFF) {
// three continuation bytes
chars[3] = 0x80 | (code & 0x3F); code = (code >> 6);
chars[2] = 0x80 | (code & 0x3F); code = (code >> 6);
chars[1] = 0x80 | (code & 0x3F); code = (code >> 6);
chars[0] = 0xF0 | (code & 0x7); chars[4] = ' ';
} else {
// unicode replacement character
chars[2] = 0xEF; chars[1] = 0xBF; chars[0] = 0xBD;
chars[3] = ' ';
}
}
int main ()
{
typedef std::codecvt<wchar_t,char,std::mbstate_t> facet_type;
std::locale mylocale;
const facet_type& myfacet = std::use_facet<facet_type>(mylocale);
char mystr[5];
GetUnicodeChar(225, mystr);
// prepare objects to be filled by codecvt::in :
wchar_t pwstr[sizeof(mystr)]; // the destination buffer (might be too short)
std::mbstate_t mystate = std::mbstate_t(); // the shift state object
const char* pc; // from_next
wchar_t* pwc; // to_next
// translate characters:
facet_type::result myresult = myfacet.in (mystate,
mystr, mystr+sizeof(mystr), pc,
pwstr, pwstr+sizeof(mystr), pwc);
if ( myresult == facet_type::ok )
{
std::wcout << L"Translation successful: ";
std::wcout << pwstr << std::endl;
}
return 0;
}
问题是,当我向GetUnicodeChar
函数提供数字225
(unicode字符á
的十进制表示)时,OSX上的输出是正确的,因为它显示字母á
,但在Windows上它显示字符├í
。但我认为Windows内部使用UTF-16,这就是为什么我认为这应该工作。
您需要首先设置_O_U16TEXT模式:
_setmode(_fileno(stdout), _O_U16TEXT);
更多信息请访问Michael Kaplain的旧博客:http://www.siao2.com/2008/03/18/8306597.aspx
相关文章:
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 从/到 UTF-8/UTF-16 的转换需要(例如:utf8 -> 代码点,然后代码点到 utf16)或(例如:utf8 -> utf16)?
- 通过分隔符分隔包含 UTF-16 BE 文本的uint8_t数组
- 如何从Little Endian UTF-16编码字节中获取C++std::string
- C++ UTF-8/ASCII to UTF-16 in MFC
- 如何C++ WCOUT UTF-16 编码的字符数组?
- 在这种情况下,UTF-16 和 UTF-32 的 BOM 是强制性的
- 查找十六进制字符串是 utf-8 或 utf-16
- 如何在C 17中读取UTF-16文本文件
- 在 Linux 中将 UTF-32 宽字符转换为 UTF-16 宽字符以获取补充平面字符
- C 14:UTF-8/UTF-16与本机字符编码之间的转换
- UTF-16 流中的 CRLF 错误?
- Windows的unicode数据类型使用什么unicode编码(UTF-8、UTF-16等)
- 可以将 UTF-8/UTF-16 选项传递给从C++调用的 JVM
- UTF 16 到 UTF8,使用 C++ 中的 utf8 库
- 使用标准C++无线流读取UTF-8文本并转换为UTF-16
- 将字节数组从UTF-16转换为UTF-8
- 如何将UTF-16中的字符串转换为C 中的UTF-8
- C++将UTF-8字符串作为UTF-16输出到std::cout
- Windows CMD不能正确输出UTF-16