C ++ exit the loop by pressing a key at any time

What I have is a loop that should read the result on one hardware every 500 milliseconds. This part is working fine. However, when I try to enter cin.get to select the "n" key to stop the loop, I get only as many outputs as the number of keystrokes to this point. If I press any keys (except "n") several times and then type, I get a few more outputs. I need the loop to continue the loop without any interaction until I want it to stop.

Here is the code:

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

My output is as follows (there are two keystrokes to go to this stage in the program), if I do not press a few more keys, then type:

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

, , .

!

+1
2

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 ++. . , .

+5

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

, . , , , .

cin.get() , .

+1

Source: https://habr.com/ru/post/1662488/


All Articles