Well, I have got a file with cyrillic characters. I am loading it, getting a string from it and then trying to display it with sf::Text. That's what my code looks like:
#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;
}
but this does only display strange characters.
This one is working:
#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;
}
Your problem has nothing to do with SFML, you are just reading your file incorrectly.
C++ uses wide strings (
std::wstring
) to represent UNICODE. This is not UTF-8. To read astd::wstring
from an UTF-8 encoded file, please read Read Unicode UTF-8 file into wstring and use the second answer.In case the order changes over time, that would be the one that tells you to use this function:
Once you have obtained a valid
std::wstring
from your file, you should be able to use it with SFML without problems.