是否可以对用户输入进行"loop interrupt"?
Is it possible to have a "loop interrupt" with user input?
这可能已经在某处得到了答案,我似乎可以找到答案。无论如何,我正在制作一个循环一定次数的程序,但是我希望程序在用户点击空格键后接受用户的输入,以触发用户将输入某些内容的事实。现在我的逻辑可能不对,但这就是我正在尝试的。
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.
}
相关文章:
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- "Ill-defined for-loop - loop executes infinitely" (MSVC C6295)
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- g++ -O3 为 loop 创建了奇怪的指令 - 两个具有相同 asm 的版本
- For-loop或std::any_of,我应该使用哪一个?
- 什么是'do while loop'的真实应用?
- loop() 函数之外的无限循环
- 如何在 Arduino 延迟期间在 void loop() 中使用 serial.available()?
- 在"for loop"中使用GOTOXY定位
- 如果用户输入数字 <0,我如何停止" while loop "?
- 如何在 Skylake 架构上最大化 sqrt-heavy loop 的指令级并行性?
- 在这种情况下,我将如何继续 1 到 360 的"for loop"处理指针和地址?
- C++ For Loop在过程中被跳过了.如何解决?
- 如何增加"for loop"呈现的结果?
- "Loop will run at most once (loop increment never executed)" C++
- 叮叮当当的'range-loop-analysis'诊断是关于什么的?
- C++ cin.ignore and getline in while loop
- 是否可以对用户输入进行"loop interrupt"?
- Waiting for interrupt-loop