Home > Back-end >  Why is ^[[A printing and need of pressing enter?
Why is ^[[A printing and need of pressing enter?

Time:12-25

#include <iostream>

int main() {
    bool con = true;
    while (con) {
        if (getchar() == '\033') {
            getchar();
            switch(getchar()) {
                case 'A':
                    std::cout << "Up arrow" << std::endl;
                    break;
                case 'B':
                    std::cout << "Down arrow" << std::endl;
                    break;
                case 'C':
                    std::cout << "Right arrow" << std::endl;
                    break;
                case 'D':
                    std::cout << "Left arrow" << std::endl;
                    break;
            }
        }
    }
}

To replicate: Press any arrow key multiple times Press enter Then it will print

I'm trying to make a console game so it would be nice for it to work.

CodePudding user response:

This is just how terminal input works on most operating systems. It is the operating system itself that handles keyboard input, and collects typed input into an internal buffer; the backspace key, and perhaps other special keys, provide the means for editing partially-entered text.

Only the Enter key results in the application receiving the entered text, post-editing. So, for example, typing "ab", pressing backspace twice, and then typing "cd" followed by Enter results in the application receiving only "cd\n" as input.

This means that the application is not going to receive any typed input until Enter is pressed.

Most operating system provide means to enable direct, or "raw" terminal input, with keystrokes being received directly by the application as soon as it is entered. On most operating system there are additional operating system-specific libraries that provide additional convenient ways of handling raw terminal input and output. You'll need to consult the documentation for your operating system for more information.

  •  Tags:  
  • c
  • Related