是否可以通过用户输入进行“循环中断”?

时间:2017-11-13 21:52:04

标签: c++

这可能已在某处得到解答,我似乎可以找到答案。无论如何,我正在制作一个循环一定数量的程序,但是我希望程序在他们点击一个空格键之后接受用户的输入以触发用户输入内容的事实。现在我的逻辑可能已关闭,但这正是我正在尝试的。

  for ( int i = 0 ; i < length (user input from before); i++){
     do{
        cout << "Hello World" << endl;
     }while(cin.getch() == ' ');
  }

从我看到的程序开始,每次我的迭代器增加时它都会停止。我有点确定为什么它每次停止的逻辑,但是如何使它循环并且只在用户点击空格键时停止?

1 个答案:

答案 0 :(得分:1)

getch是一个阻塞函数,即如果输入缓冲区为空,它会阻塞当前线程并等待用户输入。如果你想同时有一些工作,你必须产生一个单独的线程。请参阅以下用于为“worker”启动新线程的代码,而主线程则等待用户输入。希望它有所帮助。

#include <iostream>
#include <thread>

struct Worker {
    Worker() : stopped(false) {};
    void doWork() {
        while (!stopped) {
            cout << "Hello World!" << endl;
        }
        cout << "Stopped!" << endl;
    }
    atomic<bool> stopped;

};

int main(){

    Worker w;
    thread thread1(&Worker::doWork,&w);

    int c;
    while ((c = getchar()) != ' ');

    w.stopped = true;

    thread1.join();  // avoid that main thread ends before the worker thread.
}