c++ - 显示文件中的西里尔文本

标签 c++ file utf-8 sfml cyrillic

好吧,我有一个包含西里尔字符的文件。我正在加载它,从中获取一个字符串,然后尝试用 sf::Text 显示它。这就是我的代码的样子:

#include <iostream>
#include <SFML/Graphics.hpp>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"Learn me");
    sf::Text before;
    wifstream lvl;
    lvl.open("text.txt");
    sf::Font font;
    font.loadFromFile("CODE2000.ttf");
    before.setFont(font);
    before.setCharacterSize(20);
    before.setColor(sf::Color(150,150,150));
    wstring stri;
    getline(lvl,stri);
    before.setString(stri);
    while(window.isOpen()){
        sf::Event event;
        while(window.pollEvent(event)){
            switch(event.type){
        case sf::Event::Closed:
            window.close();
            }
        }

        window.clear();
        window.draw(before);
        window.display();
    }
    lvl.close();
    return 0;
}

但这只会显示奇怪的字符。

这个正在工作:

#include <iostream>
#include <SFML/Graphics.hpp>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"Learn me");
    sf::Text before;
    wifstream lvl;
    lvl.open("text.txt");
    sf::Font font;
    font.loadFromFile("CODE2000.ttf");
    before.setFont(font);
    before.setCharacterSize(20);
    before.setColor(sf::Color(150,150,150));
    wstring stri;
    getline(lvl,stri);
    sf::String text;
    text=sf::String::fromUtf8(begin(stri),end(stri));
    before.setString(text);
    while(window.isOpen()){
        sf::Event event;
        while(window.pollEvent(event)){
            switch(event.type){
            case sf::Event::Closed:
                window.close();
            }
        }

        window.clear();
        window.draw(before);
        window.display();
    }
    lvl.close();
    return 0;
}

最佳答案

您的问题与 SFML 无关,您只是错误地读取了文件。

C++ 使用宽字符串 (std::wstring) 来表示 UNICODE。这不是 UTF-8。要从 UTF-8 编码文件中读取 std::wstring,请阅读 Read Unicode UTF-8 file into wstring并使用第二个答案。

如果顺序随着时间的推移而改变,那将是告诉您使用此功能的那个:

#include <sstream>
#include <fstream>
#include <codecvt>

std::wstring readFile(const char* filename)
{
    std::wifstream wif(filename);
    wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
    std::wstringstream wss;
    wss << wif.rdbuf();
    return wss.str();
}

从文件中获得有效的 std::wstring 后,您应该能够毫无问题地将它与 SFML 一起使用。

关于c++ - 显示文件中的西里尔文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37507044/

相关文章:

c++ - 使用 boost::spirit 时无法转换 boost::variant 中的 boost::fusion 结构

c++ - If 语句似乎没有检查语句中的其他 &&

macos - 在 Swift 中逐行读取文件/URL

java - Unicode 字符变成问号

html - utf-8是字符集还是编码?

c++ - 我可以在 OpenCL 内核中嵌入 C++ 类吗?

c++ - 如何将元函数应用于可变模板类的模板类型?

python - 将 xml 节点和子节点复制到新的 xml 文件

java - 在Java中使用MappedByteBuffer读取文件的每一行

netbeans - 强制 Netbeans 对项目外部的文件使用 UTF8