#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
sf::Font font;
font.loadFromFile("font.ttf");
/*Old school (for loops would be better but you must know the capacity of your array)*/
/*
sf::Text npc_text[10]; //10, magic number that the program will soon forget, leaving you without knowing the array's capacity
npc_text[0].setFont(font);
npc_text[0].setString("greetings sire1");
npc_text[0].setPosition(0, 0);
npc_text[1].setFont(font);
npc_text[1].setString("greetings sire2");
npc_text[1].setPosition(100, 100);
*/
/**/
/*C++ (this standard template saves the vector's capacity and can do a lot of neat stuff I won't cover)*/
std::vector<sf::Text> npc_text(10);
float pos = 0;
for (auto &text : npc_text)
{
text.setFont(font);
text.setPosition(0.f, pos);
text.setString("Greetings sire!");
pos += 32.f;
}
/**/
sf::RenderWindow window(sf::VideoMode(800, 600), "test");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
window.clear();
/*Old school (for loops ....)*/
/*
window.draw(npc_text[0]);
window.draw(npc_text[1]);
*/
/**/
/*C++ (for range loops, how convenient!)*/
for (auto& text : npc_text)
{
window.draw(text);
}
/**/
window.display();
}
}
return 0;
}
http://en.cppreference.com/w/cpp/container/vector As you can see there are many features you might or might not need, but the most important thing is that in case of an error, the sf::Text's destructor will be called, preventing annoying leaks. I'm not very good at explaining programming but I hope you'll understand that most of C style code has caveats that can be overcome by c++ classes and templates.
Edit: I forgot to tell you that your code works, try commenting the C++ bits and uncommenting the C style bits
Edit: about your
posted code that crashes in
setFont from the
documentation:
The font argument refers to a font that must exist as long as the text uses it. Indeed, the text doesn't store its own copy of the font, but rather keeps a pointer to the one that you passed to this function. If the font is destroyed and the text tries to use it, the behaviour is undefined.
It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).