c ++随时通过按键突破循环

Vic*_*Nik 1 c++ loops keypress infinite-loop

我这里有一个循环,它应该每500毫秒读取一台设备上的输出.这部分工作正常.但是,当我尝试引入cin.get来拾取被按下以停止循环的键"n"时,到目前为止,我只获得与按键次数一样多的输出.如果我按任意键(除了'n')几次然后输入,我会得到更多的输出.我需要的是循环保持循环,没有任何交互,直到我希望它停止.

这是代码:

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;
};
Run Code Online (Sandbox Code Playgroud)

我的输出如下(在程序中有两个按键进入此阶段)除非我按几个键然后输入:

0.5    0 // as expected
1      2 // as expected
should be more values until stopped
Run Code Online (Sandbox Code Playgroud)

我没有特别喜欢使用哪种类型的循环,只要它有效.

谢谢!

wee*_*ens 6

cin.get()是一个同步调用,它挂起当前执行的线程,直到它获得一个输入字符(你按一个键).

你需要在一个单独的线程中运行你的循环并轮询原子布尔值,你在cin.get()返回后在主线程中更改.

它可能看起来像这样:

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; 
}
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码只是给出一个想法,它使用Boost库和最新版本的标准C++库.可能无法使用这些内容.如果是这样,请使用您环境中的替代方案.

  • 对于 C++-11,可以使用“std::thread”。这里不需要使用Boost。 (2认同)