chron, std::format, and trusty sprintf

chron, std::format, and trusty sprintf

I've been taking a C++ class and I needed to display system uptime in HH:MM:SS

I ended up finding chrono which has the ability to represent scalar units of time. Since I'm given uptime in seconds, I can wrap the input in chrono::seconds object, and then extract the hours & minutes by casting to hours & minutes duration objects. chrono makes it easy to do time math, sec - h just works.

using namespace std::chrono;

long int s = 64000;
seconds sec = seconds(s);
auto h = duration_cast<hours>(sec);
auto m = duration_cast<minutes>(sec - h);
auto rs = duration_cast<seconds>(sec - (h + m));

The next problem was zero-padding the values. In environments where c++20 is available, it'll be possible to use std::format::fmt which will let you pass a formatter string which gives you control over the padding & whatever variables. It looks a bit like Rust's std::fmt

return std::format("{:02}:{:02}:{:02}", h.count(), m.count(), rs.count());

The syntax for this is so much better - and I suppose for earlier compilers you can still use that function by including this library. Though that's a bit outside my know-how and since my code is going to be compiled (and graded) by an older system - they wrote the course in 2017 or 2018 and it seems like it's just running in some VM stack that they set up for the course - I just fell back to using sprintf.

I'm including the call here for a combination of future reference & so you can see how it's simpler.

char buffer[9];
sprintf(buffer, "%02li:%02li:%02li", h.count(), m.count(), rs.count());
return std::string(buffer);

For a while I had the length of the buffer set to 8 was puzzling over why I was seeing this warning: warning: ‘sprintf’ writing a terminating nul past the end of the destination [-Wformat-overflow=]. Then I rememdered - ah right, duh, this is a C string and you need to leave a byte for nul at the end. (It's in the warning, but I forgot 🤗)

The insight I've been having over and over is that newer versions of C++ have really improved the language, compared what it was when I was first learning it, uh, a while ago.