c++ - 将包含重音字符的 UTF-8 字符串转换为 UTF-16

标签 c++ string unicode utf-8 c++17

我正在尝试将包含一些重音字符的 std::string 转换为 std::wstring,如 C++ Convert string (or char*) to wstring (or wchar_t*) 中所述。 ,但我的程序抛出错误转换异常。

我在 Windows 10 上使用 MSVC 2022 v17.4.1,语言设置为 C++17。

这是一个演示问题的最小可重现程序:

#include <iostream>
#include <string>
#include <locale>
#include <codecvt>

#pragma warning( disable : 4996  )

int main()
{
    std::string s{ "hello ê world" };
    
    try {
        std::wstring ws = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(s);
        std::wcout << ws << "\n";
    }
    catch (const std::exception& e) {
        std::cout << e.what() << "\n";
    }
}

非常感谢将上述 std::string 转换为 std::wstring 的任何帮助。

最佳答案

您需要使用 /utf-8 编译器标志进行构建并将您的文件保存为 UTF-8。

要在 Visual Studio 中将文件保存为 UTF-8,请从“另存为”对话框中选择“使用编码保存...”。

Save As dialog

您的字符串可能被读取为“hello ª world”或另一个代码页中的另一个非 UTF-8 字符串。

来自Visual Studio documentation :

If no byte-order mark is found, it assumes that the source file is encoded in the current user code page, unless you've specified a code page by using /utf-8 or the /source-charset option.

关于c++ - 将包含重音字符的 UTF-8 字符串转换为 UTF-16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74826306/

相关文章:

c++ - 为什么C++中没有定义n的sizeof(array A[n])是固定的?

c++ - Eigen 分配器在模板类中造成问题

c - 删除 C 字符串的第一部分

java - 元字符处的 String.split() +

perl - 如何在出现 "Wide character in print at X line Y"消息时立即退出 Perl 程序?

php - JavaScript 中的正则表达式修饰符/u?

c++ - 为什么使用稍后定义的另一个常量变量将表达式限定为非常量表达式

c++ - 使用命名空间作为参数的模板函数?

c++ - 如何在 C++ 中减少较小字符串中的较大字符串?可能是通过哈希?

python - 使用 PyYaml 加载特殊字符