I want to make a c++ program that runs a while loop for a defined amount of time and then exits the loop.
Having the loop doing some stuff while running and when the time set is reached it will break out of the loop. For example have the while the loop is running it will keep printing stuff on the screen and when 1 minute has passed it will exit the loop.
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
time_t now = time(nullptr);
tm* current_time = localtime(&now);
int current_minute = current_time->tm_min;
int defined_minute = current_minute + 1;
while (current_minute < defined_minute)
{
current_minute = current_time->tm_min;
}
}
I created this code and it was supposed to work but it doesn't, I tried to debug but I still don't understand why it doesn't work.
P.S. this is my first time posting a programming problem online, appreciate if someone tells me how to better put my problems in the future.
Here is the simplest answer:
This requires C++14 or C++17. If you're using C++11, substitute
minutes{1}for1min. If you're using C++03,<chrono>is not available, and you'll have to use the C API for timing, which is significantly harder to use.Here is a video tutorial on
<chrono>.