c++ breaking out of loop by key press at any time

心不动则不痛 提交于 2019-12-08 08:00:30

cin.get() is a synchronous call, which suspends the current thread of execution until it gets an input character (you press a key).

You need to run your loop in a separate thread and poll the atomic boolean, which you change in main thread after cin.get() returns.

It could look something like this:

std::atomic_boolean stop = false;

void loop() {
    while(!stop)
    {
        // your loop body here
    }
}

// ...

int main() {
    // ...
    boost::thread t(loop); // Separate thread for loop.
    t.start(); // This actually starts a thread.

    // Wait for input character (this will suspend the main thread, but the loop
    // thread will keep running).
    cin.get();

    // Set the atomic boolean to true. The loop thread will exit from 
    // loop and terminate.
    stop = true;

    // ... other actions ...

    return EXIT_SUCCESS; 
}

Note: the above code is just to give an idea, it uses Boost library and a latest version of standard C++ library. Those may not be available to you. If so, use the alternatives from your environment.

if (cin.get() == 'n')

This call will stop your loop until it receives a key from you. There by stopping your loop as you see happening.

cin.get() will sit there until it gets a keystroke from you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!