-1

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
  • 43,603
  • 11
  • 89
  • 129
  • 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

1 Answers1

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
Alec C
  • 396
  • 1
  • 14