簡體   English   中英

將包含重音字符的 UTF-8 字符串轉換為 UTF-16

[英]Convert UTF-8 string containing accented character to UTF-16

我正在嘗試將包含一些重音字符的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,請從“另存為”對話框中選擇“使用編碼保存...”。

另存為對話框

您的字符串可能被讀取為“hello ª world”或另一個代碼頁中的另一個非 UTF-8 字符串。

來自Visual Studio 文檔

如果未找到字節順序標記,則假定源文件是在當前用戶代碼頁中編碼的,除非您已使用/utf-8/source-charset選項指定了代碼頁。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM