This is part of a series of small projects and tutorials using C++ and SFML
Library version: SFML 3.0.0
C++ Standard: ISO C++20
My Base Project: https://github.com/l-paz91/SFMLProjects/blob/main/main.cpp
In this project we'll be creating a simple app that displays the current time on your system. Here's what the finished product will look like:
Step 1 - Displaying Text
So first, we need to display some text to the screen. We can do that using SF::Text.
In SFML, you need to create a font as well that you can pass to the text object, otherwise you won't be able to display anything. So let's do that as well:
Go to your project settings. Make sure your C++ standard is set to 20 as we'll be using some functions from the new chrono library.
First we'll need some new header files:
Then, inside our game loop, we need to get the current time:
Now, I'm normally not a fan of using auto ( I generally just don't like type obfuscation), however, std::chrono can return some absolutely disgusting looking type names so in that case, I allow it.
So we have the current system time but it's not in any format we can display that makes sense to humans. Let's do that:
Here, I'm using C++20's std::chrono::system_clock::now() to get the current time, which is much nicer than the old C-style time functions. The localtime_s function converts our raw time value into a structured tm format that breaks down the time into hours, minutes, seconds, and other components. This is a safer version of the older localtime function. I then use a stringstream with std::put_time to format this structured time into the desired HH:MM:SS string format, which I feel is much cleaner that manually building strings.
I'm a big fan of stringstreams and you'll see me use them a lot in my code examples. Pretty much anytime I need to do string manipulation, I use stringstreams.
Compile and done!
Exercise
As a game engine programmer, I'm all about optimisation.
Since std::chrono::system_clock::now() always returns the current time, we always have the correct clock display regardless of the framerate. But, we're getting the time and updating the text object/doing text manipulation every frame when really we don't need to (for the purposes of this exercise anyway).
Change this program to only do the time calculations and string formatting once per second.
Hint - You can use code from my previous tutorial (Displaying the Framerate) or use SFML built in types like sf::Time.
If you get stuck: Exercise Solutions. There are many ways to do this; this is just one way of doing it.