好吧,我有一个西里尔字母的文件。我正在加载它,从中获取字符串,然后尝试使用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/