随时通过按键打破c ++ [英] c++ breaking out of loop by key press at any time
问题描述
我在这里有一个循环,该循环应该每500毫秒读取一台设备上的输出.这部分工作正常.但是,当我尝试引入cin.get来拾取被按下的"n"键来停止循环时,到目前为止,我得到的输出仅是按键数.如果我多次按任何键("n"除外),然后按Enter,将获得更多输出.我需要的是循环保持循环,没有任何交互,直到我希望它停止为止.
What I have here is a loop that is supposed to read the output on a piece of equipment every 500 milliseconds. This part works fine. However, when I try to introduce cin.get to pick up the key "n" being pressed to stop the loop, I only get as many outputs as the number of key presses up to this point. If I press any keys (apart from 'n') several times followed by enter, I will get a few more outputs. What I need is the loop keep looping without any interaction until I want it to stop.
代码如下:
for(;;)
{
count1++;
Sleep(500);
analogInput = ReadAnalogChannel(1) / 51.0;
cout << count1*0.5 << " " << analogInput << endl;
outputFile << count1*0.5 << ", " << analogInput << endl;
if (cin.get() == 'n') //PROBLEM STARTS WITH THIS INTRODUCED
break;
};
除非我再按几个键,然后按回车键,否则输出如下(有2次按键进入程序的此阶段)
My output is as follows (there are 2 key presses to get to this stage in the program) unless I press a few more keys followed by enter:
0.5 0 // as expected
1 2 // as expected
should be more values until stopped
我对使用哪种循环类型没有特别的偏好,只要它可以工作即可.
I have no particular preference in which type of loop to use, as long as it works.
谢谢!
推荐答案
cin.get()是 synchronous 调用,该调用将暂停当前执行线程,直到获得输入字符(您按一个键).
cin.get() is a synchronous call, which suspends the current thread of execution until it gets an input character (you press a key).
您需要在单独的线程中运行循环并轮询原子布尔,您可以在cin.get()返回之后在主线程中更改该原子布尔.
You need to run your loop in a separate thread and poll the atomic boolean, which you change in main thread after cin.get() returns.
它可能看起来像这样:
std::atomic_boolean stop = false;
void loop() {
while(!stop)
{
// your loop body here
}
}
// ...
int main() {
// ...
boost::thread t(loop); // Separate thread for loop.
t.start(); // This actually starts a thread.
// Wait for input character (this will suspend the main thread, but the loop
// thread will keep running).
cin.get();
// Set the atomic boolean to true. The loop thread will exit from
// loop and terminate.
stop = true;
// ... other actions ...
return EXIT_SUCCESS;
}
注意:上面的代码只是一个想法,它使用Boost库和标准C ++库的最新版本.这些可能对您不可用.如果是这样,请使用您环境中的替代方法.
Note: the above code is just to give an idea, it uses Boost library and a latest version of standard C++ library. Those may not be available to you. If so, use the alternatives from your environment.
这篇关于随时通过按键打破c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!