0

I was not able to do this. What I want is this, While the code is working in real time, the user will be able to take any action he wants.

  (...)

int main (){

    time = 60; 
    string input;

    cout << "Time: " << time << endl << endl; // Time needs to decrease every second. 
    // (time--,sleep(1000))
    cout << "Input: ";
    cin >> Input; // The user can take the action he wants at this time.

  (...)
}

I'm waiting for your help, thank you.

  • 1
    not completely clear what you want that code to do. What two functions should run at the same time? What do you mean with "take any action" ? – 463035818_is_not_an_ai Mar 30 '20 at 19:13
  • In other words, while time is running out, the user can use the "cin" function, but he should see the time decreasing on the screen. –  Mar 30 '20 at 19:18
  • Maybe a duplicate to this [Running a timer while other commands are being executed c++](https://stackoverflow.com/questions/36877961), but it should be noted that the suggested solution does not work well. – t.niese Mar 30 '20 at 19:21
  • 1
    As [this question's answer](https://stackoverflow.com/questions/9053175/is-it-possible-to-set-timeout-for-stdcin) tells, you cannot use `std::cin` for your job. You may want to search other functions that take input asynchroniously. – Tudor Mar 30 '20 at 19:23
  • [is this question related?](https://stackoverflow.com/questions/6736536/c-input-and-output-to-the-console-window-at-the-same-time) – Antonin GAVREL Mar 30 '20 at 20:03
  • Thanks [is this question related?](https://stackoverflow.com/questions/6736536/c-input-and-output-to-the-console-window-at-the-same-time) this works! –  Mar 30 '20 at 20:20

1 Answers1

0

You can use std::thread to have a second thread of execution. That thread can sleep 60 times for std::chrono::seconds{1} each tick. That second thread can write to std::cout. But this can mix with the input the user is typing! This can be quite confusing. Also, after those 60 seconds the user still needs to enter something.

Formally: It's not Undefined Behavior. It won't crash.

MSalters
  • 173,980
  • 10
  • 155
  • 350