2

我这里有一个循环,它应该每 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;
};

我的输出如下(在程序中有 2 次按键才能进入此阶段),除非我再按几个键然后回车:

0.5    0 // as expected
1      2 // as expected
should be more values until stopped

我对使用哪种类型的循环没有特别的偏好,只要它有效。

谢谢!

4

2 回答 2

9

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

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

于 2013-05-05T04:29:39.047 回答
1

if (cin.get() == 'n')

此调用将停止您的循环,直到它收到您的密钥。当你看到发生时,停止你的循环。

cin.get() 将坐在那里,直到它收到您的击键。

于 2013-05-05T03:54:21.347 回答