How can I keep running a loop until the key is pressed (C++)

user3720389 picture user3720389 · Mar 6, 2015 · Viewed 8.1k times · Source

I know this question has been asked several times on the net, but I could not find any of those answers helpful.

I want to keep running a loop and break it once the user press a key (e.g. enter or esc). I don't want it to ask user any input during the process.

I have a while loop.

I am new to C++, so please answer simply.

My system is Mac OS X.

Answer

user686776 picture user686776 · Mar 6, 2015

There you go. I hope this helps.

#include <iostream>
#include <thread>
#include <atomic>

// A flag to indicate whether a key had been pressed.
atomic_bool keyIsPressed(false);

// The function that has the loop.
void loopFunction()
{
    while (!keyIsPressed) {
        // Do whatever
    }
}

// main
int main(int argc, const char * argv[])
{
    // Create a thread for the loop.
    thread loopThread = thread(loopFunction);
    // Wait for user input (single character). This is OS dependent.
#ifdef _WIN32 || _WIN64
    system("pause");
#else
    system("read -n1");
#endif
    // Set the flag with true to break the loop.
    keyIsPressed = true;
    // Wait for the thread to finish.
    loopThread.join();

    // Done.
    return 0;
}

Update: Since the flag keyIsPressed is shared between threads, I added atomic for that. Thanks to @hyde.