我正在尝试使用 SFML(只是测试运行)来显示图片。程序可以找到图片,并打开一个新窗口,但是当它打开窗口时,它只弹出半秒然后返回 1。这是代码(这只是我调整的他们的例子):
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(500, 500), "SFML works!");
sf::Texture Texture;
sf::Sprite Sprite;
if(!Texture.loadFromFile("resources/pepe.png"));
return 1;
Sprite.setTexture(Texture);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(Sprite);
window.display();
}
return 0;
}
我假设错误来自加载后的 return 1;
,但我看不出有什么问题。有人可以发布对他们有用的东西或给我一些可能出错的提示吗?
最佳答案
您的代码工作正常,除了 ;
从文件加载纹理后,无论之前发生什么,您的程序总是返回 1。
最好添加错误消息以了解发生了什么问题。
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window(sf::VideoMode(500, 500), "SFML works!");
sf::Texture Texture;
sf::Sprite Sprite;
if(!Texture.loadFromFile("resources/pepe.png")){ // there was a ; here.
// making the code below always run.
std::cerr << "Error loading my texture" << std::endl;
return 1;
}
Sprite.setTexture(Texture);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed){
window.close();
}
// you only get here when there is at least one event.
}
// but you always want to display to the screen.
window.clear();
window.draw(Sprite);
window.display();
}
return 0;
}
我的经验法则是始终用大括号括起代码块,这样您就不会犯此类错误(或者其他人更改您的代码就不太可能犯这种错误)。
关于c++ - SFML window.draw();只出现一小段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29757205/