UTF 8 字符无法正确加载

问题描述 投票:0回答:1

所以我有一个学校项目,要求您加载一个包含 utf8 字符(如“ł,ą,ż,ź,ć,...”)的文本文件,然后对该文本进行一些编辑。但问题是,如果您使用 SetConsoleOutputCp(65001),它会正确加载文件,但如果您尝试将 cin 与 ł 、 ą 等一起使用,字符就会消失。

#include <iostream>
#include <fstream>
#include <string>
#include<windows.h>
using namespace std;

string opfile(string name){
    string line;
    ifstream myfile (name);
    string tekst;
    if (myfile.is_open())
    {
        while(getline(myfile, line)) {
            tekst += line + "\n";
        }
        myfile.close();
    }

    else cout << "Unable to open file";
    return tekst;
};
int main() {
    SetConsoleOutputCP(65001);
    string file_name;
    cin >> file_name;
    cout << opfile(file_name);
    string cos;
    cin >> cos;
    cout << cos;
    return 0;
}

这是文本文件“ŁŁŁŁŁŁŁŁĄĄĄĄĄĄĄĄĄĄÓÓÓÓĆÓŹŻÓŹĆŹŻÓĆŻÓźćÓÓÓĆŹÓŻĆŻÓŹĆÓŚĄŚĄ里面的内容ÓÓĄŚÓŚĄÓÓŚÓŚĄ" 如果我稍后尝试输入此内容,则不会输出任何内容。

我尝试环顾四周,但每个人都说 SetconsoleOutput 应该可以工作。

c++ utf-8 windows-console
1个回答
0
投票

这将在带有 MSVC 的 Windows 上运行,但在带有 clang 的 MacOS 上失败,没有在 Linux 或 Windows 上的其他编译器上进行测试:

#include <iostream>
#include <fstream>
#include <string>
#include <locale>

std::string opfile(const std::string& name){
    std::string line;
    std::ifstream myfile(name);
    myfile.imbue(std::locale{".utf-8"});
    std::string tekst;
    if (myfile.is_open())
    {
        while(getline(myfile, line)) {
            tekst += line + "\n";
        }
    } else {
       std::perror(name.c_str());
    }
    return tekst;
}

int main() {
    std::locale sysDef{""}; // use system locale for stdin and stdout
    std::cin.imbue(sysDef);
    std::cout.imbue(sysDef);

    std::locale::global(std::locale{".utf-8"}); // use UTF-8 in application
    std::string file_name;
    std::cin >> file_name;
    std::cout << opfile(file_name);
    std::string cos;
    std::cin >> cos;
    std::cout << cos;

    return 0;
}

https://godbolt.org/z/PsYG6xajx

这里是我测试韩语解决方案的一些主题,并进行了完整的解释:https://stackoverflow.com/a/67819605/1387438

© www.soinside.com 2019 - 2024. All rights reserved.