显示文件中的西里尔文本

时间:2016-05-29 06:45:08

标签: 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;
}

1 个答案:

答案 0 :(得分:2)

您的问题与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一起使用。