首页 > 解决方案 > C++ 从 txt 文件中读取 UTF-8(立陶宛字母)符号并在控制台应用程序中显示它们

问题描述

我需要你帮忙。

我正在使用 Windows 10 和 Visual Studio Community 编译器。

我设法使用 wstring 和 wcout 在 C++ 控制台应用程序上显示立陶宛字母。

#include <iostream>
#include <io.h>
#include <fcntl.h>

using namespace std;
int main()
{
   _setmode(_fileno(stdout), _O_U16TEXT);
   wstring a = L"ąėėąčėį";
   wcout << a;

   return 0;
}

结果正是我想要的

在此处输入图像描述

现在我希望我的程序从Info.txt文件中读取立陶宛字母。

在此处输入图像描述

这就是我设法达到的程度。

#include <iostream>
#include <fstream>
#include <io.h>
#include <fcntl.h>
#include <string>

using namespace std;
int main()
{
   _setmode(_fileno(stdout), _O_U16TEXT);
   wstring text;
   wifstream fin("Info.txt");
   getline(fin, text);
   wcout << text;

   return 0;
}

控制台应用程序中返回的字符串显示不同的符号。 在此处输入图像描述

但是控制台应用程序中返回的字符串显示不同的符号。

我相信一个可能的解决方案

我需要在前面的 wcout 示例中的文本之前添加 L。

wstring a = L"ąėėąčėį";

但我仍然只是学习 C++,我不知道如何在 Info.txt 的示例中这样做

我需要你的帮助!

标签: c++unicodeutf-8symbolsletter

解决方案


UTF8 需要std::ifstream,不是wifstream。后者在 Windows 中用作 UTF16 文件存储(不推荐在任何系统中使用)

您可以使用SetConsoleOutputCP(CP_UTF8)启用 UTF8 打印,但这可能会遇到问题,特别是在 C++ 20 中

相反,调用_setmode并将 UTF8 转换为 UTF16。

确保记事本以 UTF8 格式保存文件(“保存”窗口中提供了编码选项)

#include <iostream>
#include <fstream>
#include <string>
#include <io.h>
#include <fcntl.h>
#include <Windows.h>

std::wstring u16(const std::string u8)
{
    if (u8.empty()) return std::wstring();
    int size = MultiByteToWideChar(CP_UTF8, 0, u8.c_str(), -1, 0, 0);
    std::wstring u16(size, 0);
    MultiByteToWideChar(CP_UTF8, 0, u8.c_str(), -1, u16.data(), size);
    return u16;
}

int main()
{
    (void)_setmode(_fileno(stdout), _O_U16TEXT);
    std::string text;
    std::ifstream fin("Info.txt");
    if (fin)
        while (getline(fin, text))
            std::wcout << u16(text) << "\n";
    return 0;
}

推荐阅读