Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Window opens then closes really fast  (Read 1979 times)

0 Members and 1 Guest are viewing this topic.

Aiden_Cohen

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • Email
Window opens then closes really fast
« on: March 23, 2018, 03:00:02 am »
I'm building a game in Sfml, and I want to print text to the display screen easier so I created a function that does it for me, but, whenever I run the function, the window opens then closes really fast, not allowing me to see the results. However, when I don't use the function to print text to the console, nothing happens, I was wondering what would help me resolve this problem

This really should be in the window section, but I can't move the question.

Here is my Code

Main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "write.h"
#include <SFML/Graphics/Font.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "SFML works!");
    sf::Font fonts;
if(!fonts.loadFromFile("bit.ttf"))
{

std::cerr << "Error loading font" << std::endl;
return EXIT_SUCCESS;
}
sf::Text word;
word.setFont(fonts);
word.setString("Hello World");
word.setFillColor(sf::Color::Red);
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(print("aiden"));
        window.display();
    }

    return 0;
}
write.h
#ifndef WRITE_H
#define WRITE_H
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Font.hpp>

sf::Text print(std::string text);



#endif

write.cpp
#include "write.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Font.hpp>

sf::Text print(std::string text)       // std::string font)
{
sf::Font fonts;
if(!fonts.loadFromFile("bit.ttf"))
{

std::cerr << "Error loading font" << std::endl;
}
sf::Text word;
word.setFont(fonts);
word.setString(text);
word.setFillColor(sf::Color::White);
return word;
}
 
« Last Edit: March 23, 2018, 03:22:13 am by Aiden_Cohen »

dmitry_t

  • Newbie
  • *
  • Posts: 18
    • View Profile
Re: Window opens then closes really fast
« Reply #1 on: March 23, 2018, 07:40:52 am »
Your print function returns a text object which refers to a font object. However the font object lifetime is limited to the print function, it it destroyed as soon as the function returns. So in the main function the just returned text refers to a non-existing font object. This  leads to undefined behavior (e.g. to a program crash).

To solve the issue you may pass the font defined in the main function into the print function. Like this:
sf::Text print(const std::string& text, const sf::Font& font); // Use the font inside

Probably you should learn about C++ objects lifetime and about passing parameters by reference :)