Please help me improve my code. Note that it runs just fine. Especially with the way I use SFML, I need lots of guidance since I've just started learning how to use this library. I'm still learning C++ as well.
main.cpp
#include <SFML/Graphics.hpp>
#include "counter.hpp"
std::string day(int num) { return (num!=1)? "s":""; } //the 's' in the word day(s) in the text displayed
int main()
{
sf::RenderWindow window(sf::VideoMode(800,300), "New Year Counter");
window.setVerticalSyncEnabled(true);
window.setPosition(sf::Vector2i(sf::VideoMode::getDesktopMode().width/2 -400, sf::VideoMode::getDesktopMode().height/2 -150)); //put window in the middle of the screen
sf::Font font;
font.loadFromFile("Beyond Wonderland.ttf");
sf::Text text;
text.setFont(font);
text.setCharacterSize(80);
text.setFillColor(sf::Color::White);
text.move(25, 10);
sf::Text counter = text; //initialize with the same attributes as text so that I won't have to write everything again.
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
window.close();
}
TimeToNewYear year;
window.clear(sf::Color::Black);
text.setString("Until New Year "+year.get_newYear()+"\n"+year.get_daysLeft()+" day"+day(std::stoi(year.get_daysLeft()))+" left\n\t\tand");
window.draw(text);
counter.setString(year.get_counter());
counter.setCharacterSize(120);
counter.setPosition(360, 140);
window.draw(counter);
window.display();
}
}
counter.hpp
#ifndef COUNTER_HPP
#define COUNTER_HPP
#include <string>
#include <ctime>
class TimeToNewYear
{
private:
time_t m_nowTime = time(0);
time_t m_tmny; //for mktime (time new year)
tm *m_locTime = localtime(&m_nowTime);
tm m_newYear {};
int m_timeLeft;
int m_daysLeft;
std::string m_counter;
void addNum(int num) //to display single digits with a 0 ex: 03
{
if(num<=9)
m_counter += "0";
m_counter += std::to_string(num);
}
public:
TimeToNewYear()
{
m_newYear.tm_mday =1;
m_newYear.tm_year = 1+ m_locTime->tm_year; //set m_newYear
m_tmny = mktime(&m_newYear);
m_timeLeft = difftime(m_tmny, m_nowTime);
//calculate days left
m_daysLeft = m_timeLeft/(24*3600);
m_timeLeft %= 24*3600;
}
std::string get_daysLeft() const { return std::to_string(m_daysLeft); }
std::string get_newYear() const { return std::to_string(m_newYear.tm_year +1900); } //tm_year is the years from 1900
std::string get_counter()
{
addNum(m_timeLeft/3600);
m_counter += ":";
m_timeLeft %= 3600;
addNum(m_timeLeft/60);
m_counter += ":";
addNum(m_timeLeft%60);
return m_counter;
}
};
#endif