从文件显示西里尔文 [英] Displaying cyrillic text from file
问题描述
好吧,我有一个西里尔字符的文件。我加载它,从它得到一个字符串,然后尝试使用sf :: Text显示它。这是我的代码看起来像:
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.
这一个正在工作:
#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;
}
推荐答案
C ++使用宽字符串( std :: wstring
)代表UNICODE。这是不是 UTF-8。要从UTF-8编码文件读取 std :: wstring
,请阅读将Unicode UTF-8文件读入wstring 并使用第二个答案。
C++ uses wide strings (std::wstring
) to represent UNICODE. This is not UTF-8. To read a std::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:
#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没有问题。
Once you have obtained a valid std::wstring
from your file, you should be able to use it with SFML without problems.
这篇关于从文件显示西里尔文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!