我正在尝试将包含一些重音字符的 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 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/