Qwerp-Derp Qwerp-Derp - 1 month ago 13
C++ Question

Trouble condensing code in C++ - SFML

This is probably going to sound like a stupid question...

I have this piece of code in C++, that uses the SFML library:

#include <SFML/Graphics.hpp>
#include <string>

void textDisplay(sf::Text& display_text, std::string display_str, sf::Font display_font, int char_size) {
display_text.setString(display_str);
display_text.setFont(display_font);
display_text.setCharacterSize(char_size);
display_text.setStyle(sf::Text::Regular);
}

int main() {
sf::RenderWindow window(sf::VideoMode(400, 400), "Game");
sf::Font arial;
if (!arial.loadFromFile("fonts/arial/arial.ttf")) {
return 0;
}

sf::Text text;
textDisplay(text, "Hello, World!", arial, 30);

sf::CircleShape shape(100.f, 10);
shape.setFillColor(sf::Color::Yellow);

while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}

window.clear();
window.draw(text);
window.display();
}

return 0;
}


Because I'm going to repeat the same four lines of code over and over when I'm trying to display the text onto an SFML screen, rather than repeating the code, I created a function (
textDisplay
) that takes in four arguments (the
Text
object itself, a string, a font, and the character size) and initializes the
Text
object for me.

For some reason, the text doesn't display - is there anything I'm doing wrong?

Some stuff:


  • The window is called
    window
    .

  • There's no error when compiled, so I have no idea where the error is.

  • The board itself is just black, there's no text on
    window
    .



If the error has to do with the function itself, can you recommend an alternative to typing the same four lines over and over again?

Answer

Found it, you were setting your text with a temporary font, since its a normal variable and not a reference/pointer:

void textDisplay(sf::Text& display_text, std::string display_str, sf::Font& display_font, int char_size) { //Just make it a reference and its done! :)
    display_text.setString(display_str);
    display_text.setFont(display_font);
    display_text.setCharacterSize(char_size);
    display_text.setStyle(sf::Text::Regular);
}
Comments