是否有任何内置函数可以在Linux中将wstring或wchar_t*转换为UTF-8?

Ami*_*yan 7 c c++ linux utf-8 wstring

我想将wstring转换为UTF-8编码,但我想使用Linux的内置函数.

是否有任何内置函数可以在Linux中通过简单的调用转换wstring或转换wchar_t*为UTF-8 ?

例:

wstring str = L"file_name.txt";
wstring mode = "a";
fopen([FUNCTION](str), [FUNCTION](mode)); // Simple invoke.
cout << [FUNCTION](str); // Simple invoke.
Run Code Online (Sandbox Code Playgroud)

Cub*_*bbi 13

如果/当您的编译器支持足够的C++ 11时,您可以使用 wstring_convert

#include <iostream>
#include <codecvt>
#include <locale>
int main()
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
    std::wstring str = L"file_name.txt";
    std::cout << utf8_conv.to_bytes(str) << '\n';
}
Run Code Online (Sandbox Code Playgroud)

在Linux上使用clang ++ 2.9/libc ++和在Windows上使用Visual Studio 2010进行测试.


Ker*_* SB 7

C++语言标准没有明确编码的概念.它只包含"系统编码"的不透明概念,其wchar_t"足够大"类型.

要从不透明系统编码转换为显式外部编码,必须使用外部库.选择的库将是iconv()(from WCHAR_Tto UTF-8),它是Posix的一部分,可在许多平台上使用,但在Windows上,WideCharToMultibyte功能可以保证生成UTF8.

C++ 11 以形式添加新的UTF8 文字std::string s = u8"Hello World: \U0010FFFF";.那些已经是UTF8,但wstring除了我描述的方式之外,它们不能与不透明接口.

有关更多背景信息,请参阅此问题.