c++keystroke

How to wait for a specific keystroke?


I'm a bit new to C++, so I beg your pardon for being a bit nooby.

Is there a function I can use to make the console pause until a specific key is pressed?

Example being:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;

    if (specific key pressed) {
        i = 1;
    } else if (other key pressed) {
        i = 2;
    }

    cout << i << endl;

    return 0;
}

The console should output 1 if the right key is pressed, and 2 if another key is.


Solution

  • What you're trying to do is a bit more complex, C++ makes use of the cin stream where the input into the console is fed into your program. Where as a key-press event would be something the operating system would handle and would vary between operating systems. So using something like this would require the user to press enter/return for the input to be received by the program.

    char key;
    std::cin >> key;
    if (key == 'a') {
        std::cout << 1;
    }
    else {
        std::cout << 2;
    }
    

    Find some answers here How to handle key press events in c++