Accepting arrow keys as input in if statements

I am a junior in high School and taking a c++ coding class. Our first assignment is to make a text based game we are allowed to use anything as input but the teacher only told us how to accept text. How would I make it so that you can press your arrow keys to say which way you would like to go within an if statement?

instead of this;
string PlayerAnswer;
cin >> PlayerAnswer;
if (PlayerAnswer == RIGHT)
cout << ("storyline") endl;
else (PlayerAnswer == LEFT)
cout << ("storyline") endl;

That is how we were shown to do it, we are using visual studio 2017 in class and on my gaming notebook at home in case that matters.

I want to swap the PlayerAnswer out for a command to take input from the arrow keys. Would the way to do keyboard inputs be any different for the nested ifs?

Thanks for the help I don't have to do with arrow keys but my teacher said it would be fine if I figured out how to and implemented it also I just want to learn how to do it.
Last edited on
The arrow keys (and function keys and some others) are special in that they send more than one "char" per keypress. I don't run Windows, so I don't know if it sends two chars or three.

So try running this program four times. Each time, press a different arrow key. What results do you get for each arrow key?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <conio.h>
using namespace std;

int main() {
    int ch;
    ch = _getch();
    cout << ch << '\n';
    ch = _getch();
    cout << ch << '\n';
    ch = _getch();
    cout << ch << '\n';
}

I'm a begginer so im just here to observe but i've already tried it.
up=224,72
right=224,77
down=224,80
left=224,75
Try this and see if it prints the correct directions for the arrows. Hit q (or Ctrl-C) to stop.

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
#include <iostream>
#include <conio.h>
using namespace std;

int main() {
    bool loop = true;
    while (loop) {
        int ch = getch();
        if (ch == 224) {
            ch = getch();
            switch (ch) {
            case 72: cout << "up\n";    break;
            case 80: cout << "down\n";  break;
            case 77: cout << "right\n"; break;
            case 75: cout << "left\n";  break;
            default: cout << "unknown\n";
            }
        }
        else {
            cout << char(ch) << '\n';
            if (char(ch) == 'q')
                loop = false;
        }
    }
}

Last edited on
It works
Good. Thanks for trying it.
Topic archived. No new replies allowed.