简体   繁体   English

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

[英]C++ Read UTF-8 (Lithuanian letters) symbols from txt file and show them in console application

I need you help.我需要你帮忙。

I'm using Windows 10 and Visual Studio Community compiler.我正在使用 Windows 10 和 Visual Studio 社区编译器。

I managed to get Lithuanian letter to show on C++ console application using wstring and wcout.我设法使用 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;
}

Result is exactly what I wanted it to be结果正是我想要的

在此处输入图片说明

Now I want my program to read Lithuanian letters from Info.txt file.现在我想让我的程序从Info.txt文件中读取立陶宛字母。

在此处输入图片说明

This is how far I managed to get.这是我设法达到的程度。

#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;
}

Returned string in console application shows different simbols.控制台应用程序中返回的字符串显示不同的符号。 在此处输入图片说明

But the returned string in console application shows different simbols.但是控制台应用程序中返回的字符串显示不同的符号。

In my belief a possible solution在我看来,一个可能的解决方案

I need to add L before the text like in previous example with wcout.我需要像前面的 wcout 示例一样在文本之前添加 L。

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

But I'm still just learning C++ and I don't know how to do so in example with Info.txt但我仍然只是在学习 C++,我不知道如何在 Info.txt 的例子中这样做

I need your help!我需要你的帮助!

UTF8 needs std::ifstream , not wifstream . UTF8 需要std::ifstream ,而不是wifstream The latter is used in Windows as UTF16 file storage (not recommended in any system)后者在 Windows 中用作 UTF16 文件存储(不推荐在任何系统中使用)

You can use SetConsoleOutputCP(CP_UTF8) to enable UTF8 printing, but that can run in to problems, specially in C++ 20您可以使用SetConsoleOutputCP(CP_UTF8)来启用 UTF8 打印,但这可能会遇到问题,特别是在 C++ 20 中

Instead, call _setmode and convert UTF8 to UTF16.相反,调用_setmode并将 UTF8 转换为 UTF16。

Make sure notepad saves the file in UTF8 (encoding option is available in Save window)确保记事本以 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM