rub*_*nvb 3 c++ winapi utf-8 utf-16 wide-api
是否好/安全/可以使用微小的utfcpp库将我从宽Windows API(FindFirstFileW等)返回的所有内容转换为使用utf16to8的有效UTF8表示?
我想在内部使用UTF8,但是无法获得正确的输出(在另一次转换或普通cout之后通过wcout).普通的ASCII字符当然可以工作,但是ñä搞砸了.
还是有更简单的选择?
谢谢!
更新:感谢Hans(下面),我现在可以通过Windows API进行简单的UTF8 < - > UTF16转换.双向转换有效,但UTF16字符串中的UTF8有一些额外的字符可能会在以后引起我的麻烦......).我将在这里分享它纯粹的友好:)):
// UTF16 -> UTF8 conversion
std::string toUTF8( const std::wstring &input )
{
// get length
int length = WideCharToMultiByte( CP_UTF8, NULL,
input.c_str(), input.size(),
NULL, 0,
NULL, NULL );
if( !(length > 0) )
return std::string();
else
{
std::string result;
result.resize( length );
if( WideCharToMultiByte( CP_UTF8, NULL,
input.c_str(), input.size(),
&result[0], result.size(),
NULL, NULL ) > 0 )
return result;
else
throw std::runtime_error( "Failure to execute toUTF8: conversion failed." );
}
}
// UTF8 -> UTF16 conversion
std::wstring toUTF16( const std::string &input )
{
// get length
int length = MultiByteToWideChar( CP_UTF8, NULL,
input.c_str(), input.size(),
NULL, 0 );
if( !(length > 0) )
return std::wstring();
else
{
std::wstring result;
result.resize( length );
if( MultiByteToWideChar(CP_UTF8, NULL,
input.c_str(), input.size(),
&result[0], result.size()) > 0 )
return result;
else
throw std::runtime_error( "Failure to execute toUTF16: conversion failed." );
}
}
Run Code Online (Sandbox Code Playgroud)
Win32 API已经具有执行此操作的功能,WideCharToMultiByte()具有CodePage = CP_UTF8.使您不必依赖其他库.
你通常不能在wcout中使用结果.它的输出转到控制台,由于传统原因,它使用8位OEM编码.您可以使用SetConsoleCP()更改代码页,65001是UTF-8(CP_UTF8)的代码页.
你的下一个绊脚石将是用于控制台的字体.你将不得不改变它,但找到一个固定音高的字体并拥有一整套字形来覆盖Unicode将是困难的.当您在输出中获得方形矩形时,您会看到字体有问题.问号是编码问题.
| 归档时间: |
|
| 查看次数: |
2359 次 |
| 最近记录: |