C++ UTF-8 瑞典语字符读取为 ASCII
C++ UTF-8 Swedish Characters are Read as ASCII
有一个C++程序,我需要添加读取文件的功能。 我发现它不适用于欧洲特殊字符。 我正在使用的例子是瑞典字符。
我将代码更改为使用宽字符,但这似乎没有帮助。
我正在阅读的示例文本文件包含以下内容:
"NEW-DATA"="Nysted Vi prøver lige igen"
这是在Windows和Nodepad上说这个文件正在使用UTF-8编码。
在 Visual Studio 中,调试时,读取的字符串将显示为使用 ASCII:
"NEW-DATA"="Nysted Vi prøver lige igen"
我更改了代码以使用"宽"方法:
std::wifstream infile;
infile.open(argv[3], std::wifstream::in);
if (infile.is_open())
{
std::wstring line;
while (std::getline(infile, line))
{
....
我还需要做些什么来让它正确识别 UTF-8 吗?
您可以将 UTF-8 内容读取为 ASCII 文本,但必须将它们转换为宽字符,以允许 Visual Studio 将其解释为 unicode。
这是我们用于此的常用函数:
BSTR UTF8ToBSTR(char const* astr)
{
static wchar_t wstr[BUFSIZ];
// Look for the funtion description in MSDN.
// Use of CP_UTF8 indicates that the input is UTF8 string.
// Get the size of the output needed for the conversion.
int size = MultiByteToWideChar(CP_UTF8, 0, astr, -1, NULL, 0);
// Do the conversion and get the output.
MultiByteToWideChar(CP_UTF8, 0, astr, -1, wstr, size);
// Allocate memory for the BSTR and return the BSTR.
return SysAllocString(wstr);
}
您必须添加代码来释放调用SysAllocString(wstr)
分配的内存。
例如
BSTR bstr = UTF8ToBSTR(...);
// Use bstr
// ...
// Deallocate memory
SysFreeString(bstr);
正在发生的事情是,您有一个 UTF-8 编码的文件,但您正在尝试读取它,就好像它由宽字符组成一样。那行不通。如您所见,BOF标记已逐字读取到字符串中,因此很明显,您使用的机制不包含任何尝试对字符进行任何类型的解析和UTF-8字节对解码的逻辑。
宽字符和 UTF-8 是两个根本不同的东西。 您不可能仅通过以下方法读取 UTF-8 扑通一声
wchar_t
(或std::wstring
(并阅读。你是 需要使用某种 Unicode 库。有std::wstring_convert
C++11 中(但这需要工具支持(和 有手动mbstowcs()/wcstombs()
路线。无处不在 最好使用库。
源: https://www.reddit.com/r/cpp/comments/108o7g/reading_utf8_encoded_text_files_to_stdwstring/
我认为mbstowcs()/wcstombs()
是MicrosoftMultiByteToWideChar()
和MultiByteToWideChar()
的便携式替代品。
- C++ UTF-8 瑞典语字符读取为 ASCII
- 使用 std::ifstream 读取 ASCII 文本文件C++
- 如何从字符中读取ASCII值并将其转换为十六进制格式的字符串
- 读取字符 ASCII 值并将其记录到矢量
- 如何在C++中读取带有ifstream的替换字符?(ASCII 中的 SUB)
- 读取 ASCII 文件的有效方法
- 将 ASCII 文件读取到C++ std::string 中的最简单方法是什么?
- ASCII 和二进制 - 按原样显示,但读取返回垃圾
- 从文件中读取ascii字符,然后将其转换为一个位字符串c++
- 使用cin.get()读取扩展ASCII
- STL文件的哪种格式读取速度更快:ascii还是二进制
- 在C++中将ASCII读取到数组中
- 如何在 Linux 上使用 std::ifstream 从文件中读取非 ASCII 行
- 从c++文件中读取ASCII和二进制
- 从文件中读取数字并将其存储为十进制而不是c++中的ASCII
- 我如何读取整数并将其转换为ASCII字符和
- 我正在写0到255个ascii字符,并试图逐个字符读取它,但不能在第25个字符后读取
- 读取非ascii文件名的文件
- 在C++中读取12-15GB ASCII文件的最佳方式
- 字符编码-当读取超过127个ASCII值时,C++cin失败