0
#include <iostream>
#include <conio.h>
#include <chrono>
#include <thread>

using namespace std;

int main() {
do {
   time_t curr_time = time(NULL);
  system("CLS");
  tm* tm_local = localtime(&curr_time);
  cout << "Current time : " << tm_local->tm_hour << ":" << tm_local->tm_min << ":" << tm_local->tm_sec << endl;
  cout << "To exit the clock click space" << endl;
  this_thread::sleep_for(chrono::seconds(1));
  char ch = getch();
  if (ch == ' ') {
    system("CLS");
    goto main;
  }
 } while (true);
}

I have a problem when I execute the program the time is frozen but when I click space it goes to the main as intended

main problem: the time freezes and does not update every second

I was expecting to update the time every second, I have tried using a while loop.

DaGreyKar
  • 1
  • 2

1 Answers1

0

A few comments on your code:

  • never use goto!
  • do not use using namespace std;
  • try to avoid calls to "system"
  • You can go back to beginning of line in output with '\r'
  • There is no platform independent wait for a key to be hit, but you can exit your program with break (ctrl+c)

Demo here : https://onlinegdb.com/Z6vMyjipm

#define _CRT_SECURE_NO_WARNINGS // needed by msvc to suppress issue with std::localtime which is not safe.

#include <chrono>
#include <iostream>
#include <iomanip>
#include <thread>
#include <string_view>

using namespace std::chrono_literals;

std::string time_to_str(const std::chrono::system_clock::time_point& time, const std::string_view format)
{
    std::time_t tt = std::chrono::system_clock::to_time_t(time);
    std::tm tm = *std::localtime(&tt); //Locale time-zone, usually UTC by default.
    std::stringstream ss;
    ss << std::put_time(&tm, format.data());
    return ss.str();
}

int main()
{
    while (true)
    {
        // in C++20 with format support you can use std::format
        //auto s = std::format("{:%Y/%m/%d %H:%M:%S}", std::chrono::system_clock::now());
        auto s = time_to_str(std::chrono::system_clock::now(), "%Y/%m/%d %H:%M:%S");
        std::cout << s << "\r";
        std::cout << std::flush; // needed for onlinegdb to show output
        std::this_thread::sleep_for(1s);
    }
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19