[英]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 字符串。
如果未找到字節順序標記,則假定源文件是在當前用戶代碼頁中編碼的,除非您已使用
/utf-8
或/source-charset
選項指定了代碼頁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.