简体   繁体   中英

Keep running a program without any intervention till its asked to quit

The below code expects the user to key in a character on every loop. If I want to keep running this loop without user having to enter any character on every loop till the number 0 is keyed in, how do i achieve it.

#include<iostream>

int main()
{
    int i = 1;
    int ch = 1;
    while (ch != 0)
    {
        std::cin >> ch;
        std::cout << "Hi" << i << std::endl;
        ++i;
    }
    return 1;
}

Threading is your only possibility. Also it always requires the ENTER when you are using std::cin. This could work:

#include <future>
#include <iostream>
#include <thread>

int main(int argc, char** argv) {
    int i = 1;
    std::atomic_int ch{1};
    std::atomic_bool readKeyboard{true};

    std::thread t([&ch, &readKeyboard]() {
        while (readKeyboard) {
            int input;
            if (std::cin >> input) {
                ch = input;
                if (ch == '0') {
                    break;
                }
            }
        }
    });

    while (ch != '0') {
        std::cout << "Hi" << i << std::endl;
        ++i;
    }

    readKeyboard = false;
    t.join();
    return 1;
}

You can do this but you will have to use threads. Here is the minimal example how to achive this behaviour. Please note that you will need C++11 at least.

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

int main() 
{
    std::atomic<bool> stopLoop;

    std::thread t([&]() 
    { 
        while (!stopLoop) 
        { 
            std::cout << "Hi"; 
        }

    });

    while (std::cin.get() != '0') //you will need to press enter after pressing '0'
    {
        ; //empty loop, just wait until there is 0 on input
    }
    stopLoop = true; //this stops the other loop
}

Other options will be to dive into OS specific libraries. You must now that C++ doesn't have any kind of non-blocking I/O in standard library and for most time you will have to press <ENTER> to have any input in input stream (std::cin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM