【发布时间】:2011-03-20 18:32:50
【问题描述】:
使用小型 utfcpp 库将我从广泛的 Windows API(FindFirstFileW 等)返回的所有内容转换为使用 utf16to8 的有效 UTF8 表示是否很好/安全/可行?
我想在内部使用 UTF8,但无法获得正确的输出(在另一次转换后通过 wcout 或普通 cout)。普通的 ASCII 字符当然可以,但 ñä 会搞砸。
或者有没有更简单的选择?
谢谢!
更新:感谢 Hans(下),我现在可以通过 Windows API 轻松实现 UTF8UTF16 转换。两种方式转换工作,但来自 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." );
}
}
【问题讨论】:
标签: c++ winapi utf-8 utf-16 wide-api