Video Coming Soon...
39: sleep
A first version of sleep is trivial. With C++ it's about 2 lines of code to sleep for an amount of time. Where things get weird is in the parsing of the time format sleep supports. You can specify a time length as a float in scientific notation then attach a s, m, or other character to change the meaning.
The Challenge
My first version of sleep is simple enough that I'm just going to give it to you. The real challenge will be implementing the smhd (seconds, minutes, hours, days) formatting allowed on the command line. You can do things like this with sleep:
sleep 1234e-3m
To sleep for 1234e-3 minutes. You can also give it inf to have it wait forever.
The Code
Here's the code to get you started.
View Source file sleep.cpp Only
#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>
int main(int argc, char* argv[]) {
if(argc != 2) {
fmt::println("USAGE: sleep [seconds]");
return 1;
}
int time = std::stoi(argv[1]);
std::chrono::seconds wait_for{time};
std::this_thread::sleep_for(wait_for);
}
The majority of your work will be reading the command line arguments and converting them to std::chrono::duration based on what you parse.
The Discussion
Handling time almost always sucks. I can't think of any language that gets time right, and that's mostly because humans have incredibly arbitrary and stupid ways of dealing with time they've inherited from thousands of years of history. The C++ std::chrono API is decent enough, but don't be surprised if you run into some strange edge cases, or some strange person who absolutely hates it (but who can't tell you something better to use).
Further Study
Can you devise a better way to specify these times? Maybe something more human readable?
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.