是否可以对用户输入进行"loop interrupt"?

Is it possible to have a "loop interrupt" with user input?

本文关键字:loop interrupt 输入 用户 是否      更新时间:2023-10-16

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

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

从我看到的程序所做的事情来看,每次我的迭代器增加时,它都会停止。我有点确定为什么它每次都停止的逻辑,但是我如何让它循环并且仅在用户点击空格键时才停止?

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.
}