0

I am writing code that terminates by entering e or t , and I want everything to work under two minuets, but I cant get things to work once I include the delay or sleep, tried using the chrono lib

int main()
{
    string ee;
    int x=5, y=3;
    while (true) {
        std::cout <<y<< std::endl;
        cout <<x<< std::endl;
        cin >>ee;
        if (ee =="e" { break;}
        if (ee =="e" { break;}
        if (ee =="E" { break;}
        if (ee =="T" { break;}
    }
}
user438383
  • 5,716
  • 8
  • 28
  • 43
Zulu
  • 1
  • 1
  • 1
    You can implement it by getting the current time before the loop, then check the time each iteration and break from the loop if 2 minutes passed. – wohlstad May 05 '22 at 08:52
  • You could use a thread to exit your process after a timer. But that could kill the main thread while it's waiting for input which isn't really nice. Other than that there's no plain standard C++ solution to your problem. – Some programmer dude May 05 '22 at 08:52
  • Yes, but it depends on your operating system because it is not a standard part of the C language itself. – user253751 May 05 '22 at 09:19

1 Answers1

1

The elaborate on my comment above:

There is no standard c++ function to limit the runtime of a program as such. You'll need to implement such a mechanism, according to your specific needs.

My solution below assumes that you do not intend to abort the std::cin operation (cin >>ee;). I assumed that the usage of std::cin was just to simulate some way of breaking a long iterative process.

If this is the case, you can do get a time measurement before the long process. Then in each iteration get a new time measurement and exit it if your maximum time elapsed.

Something like the following:

#include <string>
#include <iostream>
#include <chrono>
#include <thread>

int main()
{
    int x = 5, y = 3;
    auto tStart = std::chrono::steady_clock::now();
    while (true) {
        auto tNow = std::chrono::steady_clock::now();
        auto elapsedSecs = std::chrono::duration_cast<std::chrono::seconds>(tNow - tStart).count();
        if (elapsedSecs >= 120)
        {
            // 2 minutes or more passed => exit
            break;
        }

        // Simulate one iteration of the long process:
        std::cout << y << std::endl;
        std::cout << x << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    return 0;
}

Note: it's better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • thanks for the help any suggestion on how i can make this program terminate by entering t or e – Zulu May 05 '22 at 13:48
  • The problem is that waiting for console input with `cin` is blocking. It is not recomended to terminate such an operation. You can see here about non blocking console input: https://stackoverflow.com/questions/6171132/non-blocking-console-input-c. – wohlstad May 05 '22 at 13:52