[英]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.
如果我想继续运行此循环而无需用户在每个循环中输入任何字符,直到键入数字0,我该如何实现它。
#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.
当您使用std :: cin时,也总是需要ENTER键。 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.
请注意,您至少需要C ++ 11。
#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) 现在,您必须确保C ++在标准库中没有任何类型的非阻塞I / O,并且大多数时候您将必须按
<ENTER>
以在输入流(std :: cin)中进行任何输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.