Simple question

Just a quick simple question. How can i have an infinitely running while with operations here and there, and when the user presses the B key, the while executes break;?
The short answer is threads.

Have one thread monitoring the keyboard and, when it detects the user has pressed B, set a value.

Have one thread working and checking that value every so often. When the value is set, stop working.

C++ knows nothing of keyboards so to monitor for a keypress, you'll have to use OS functions or a library to take care of it for you.
Ehm... Im kinda new to cpp so I have no idea on how to do that. Also sorry for necro-bumping.
Maybe a piece of code i could have?
SFML has a solid, multi-platform interface for dealing with events, which includes key pressing events. Fairly beginner friendly to follow along, but you should know the basics of the language. https://www.sfml-dev.org/index.php


See "Events Explained"
https://www.sfml-dev.org/tutorials/2.4/window-events.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
sf::Event event;

// while there are pending events...
while (window.pollEvent(event))
{
    // check the type of the event...
    switch (event.type)
    {
        // window closed
        case sf::Event::Closed:
            window.close();
            break;

        // key pressed
        case sf::Event::KeyPressed:

            // logic if you press Bbutton:
            if (event.key.code == sf::Keyboard::B)
            {
                std::cout << "the B key was pressed" << std::endl;
            }

            break;

        // we don't process other types of events
        default:
            break;
    }
}


Edit: But I realize now that SFML might not be what you want, since you're only talking about the console. See the Windows-only section if you're working with windows, otherwise I'm not sure.

Windows-only?
See threads such as:
http://www.cplusplus.com/forum/windows/105443/
https://stackoverflow.com/questions/8640208/what-is-the-fastest-way-to-determine-a-key-press-and-key-holding-in-win32
Last edited on
Topic archived. No new replies allowed.