0

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.

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • By "specific key" are you referring to a specific character, or something with no visual representation like an arrow key? – 4castle Mar 20 '17 at 02:32
  • 1
    `int i - 0;` makes little sense. Please stop "typing" code here, and instead paste it from your IDE. – Vada Poché Mar 20 '17 at 02:36
  • Without knowing anything about your console, there's no way we could know whether it's possible for it to do this or, if so, how to make it do that. – David Schwartz Mar 20 '17 at 02:38
  • It's platform dependent. If it's Windows take a look at these threads http://stackoverflow.com/questions/24708700/c-detect-when-user-presses-arrow-key http://stackoverflow.com/questions/2067893/c-console-keyboard-events – pcodex Mar 20 '17 at 02:48

2 Answers2

0

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

Community
  • 1
  • 1
avlec
  • 396
  • 1
  • 15
0

Works on Windows only:

#include <iostream>
#include <vector>
#include <Windows.h>


char GetKey(std::vector<char> KeysToCheckFor)
{
    while (true)
    {
        Sleep(1);
        for (int i = 0; i < KeysToCheckFor.size(); i++)
        {
            if (GetKeyState(toupper(KeysToCheckFor[i])) < 0) { return KeysToCheckFor[i]; }
        }
    }
}

int main()
{
    std::cout << "Press one of the keys: a,b,c\n";
    char returnedkey = GetKey({ 'a', 'b', 'c' });
    std::cout << returnedkey << " has been pressed!\n";
    system("pause");
}
Alex
  • 552
  • 3
  • 15