Hi, I'm trying to make my program that I'm making for school change backgrounds every five seconds. My code compiles just fine, but the program crashes immediately. I've managed to debug it enough to where I know what's causing the problem, but I can't figure out how. Heres my code:
BackgroundManager.hpp:
#include <memory>
#include <iostream>
#include <sstream>
#include "Background.hpp"
#include "GameState.hpp"
class BackgroundManager //manages the initialization and switching of different backgrounds
{
public:
BackgroundManager() : resourceFilepath("Resources/") {}; //sets resourcefilepath equal to Resources/
~BackgroundManager() {};
void initBackgrounds(); //initializes backgrounds
void switchBackgrounds(sf::RenderWindow& screen, int state); //function to switch between backgrounds
static std::unique_ptr<Background> createBackground() { return std::unique_ptr<Background>(new Background); }
private:
std::unique_ptr<Background> background;
int randBackgroundNum;
const std::string& resourceFilepath; //const reference to a string for the resource file path
std::ostringstream backgroundNum; //a stream used to collect background numbers and initialize them
sf::Clock clock; //clock for measuring team in between backgrounds
};
BackgroundManager.cpp:
#include "BackgroundManager.hpp"
void BackgroundManager::initBackgrounds()
{
srand(time(NULL)); //seed random number
try
{
background = createBackground();
std::cout << "Successfully created a background." << std::endl;
}
catch (std::bad_alloc& ba)
{
std::cerr << ba.what() << " at background manager" << std::endl;
}
catch (...)
{
std::cout << "An unknown exception occured." << std::endl;
}
}
void BackgroundManager::switchBackgrounds(sf::RenderWindow& screen, int state)
{
switch (state)
{
case 0: //Case introstate
randBackgroundNum = rand() % 5; //get a number 0 - 5
break;
case 1: //Case historystate
randBackgroundNum = rand() % 10 + 6; //get a number 6 - 10
break;
}
backgroundNum << randBackgroundNum; //place the randBackgroundNum in a stream for file usage
background->init(resourceFilepath + backgroundNum.str() + ".jpg"); //initialize background with given random filepath >>>>>>PROBLEM IS HERE THAT CAUSES CRASH <<<<<<
clock.restart(); //restart the clock
while (clock.getElapsedTime().asSeconds() < 5.0f) //while 5 seconds haven't passed, keep drawing current background
screen.draw(background->getSprite());
}