c++ Console Configuration Error (Novice)

Asked 2 years ago, Updated 2 years ago, 27 views

c++

2022-09-22 19:55

2 Answers

Why is it that the output statement comes out immediately even though you didn't enter the enter key twice?

GetAsyncKeyState() returns the status of that key at the time it is called. If GetAsyncKeyState() is called several times at short intervals during the process of pressing and standing up the keyboard, the function will return multiple pressed states.

In other words, even if you think you've typed a keyboard once, the code actually gets a pressed state of the keyboard, so it can be treated as multiple times.

To solve this problem, it may be better to judge a pressed and floated moment, such as a KEY_UP event, rather than reading the 'pressed' state.

A simple method is to use _kbhit() and _getch().

#include <conio.h>

int main() {
    for (;;) {
        if (!_kbhit())
            continue;
        int key = _getch();

        if (key == VK_RETURN) {
            // Processing for enter
        }
        else if (key == VK_ESCAPE) {
            // Processing for esc
        }
    }
    return 0;
}

_kbhit() sells when the keyboard is pressed. You can then import pressed keys via _getch(). If _getch() does not import the key, please note that _kbhit() will continue to return true.

Next, the second question is that I want to go to the main menu when I press the Enter key from submenu 1 and submenu 2 to return to the screen, but it keeps going into submenu 1. I wonder which part it is because of.

You can see the following code in SubMenu.cpp.

            case 2:
            {
                Main Menu ("Questionnaire 1", "Questionnaire 2", "End"); // Same as above
                p.Firstmenu();
            }break;

If you create and operate a new MainMenu like this, it will operate as follows, so it will not go back. This may cause a stack overflow.

MainMenu -> SubMenu1 -> MainMenu -> SubMenu1 -> MainMenu -> ...

It would be better to write a code to escape the while statement or to end the function in this process. If you do this, you will return to the loop from the previous MainMenu so you will do what you want.


2022-09-22 19:55

I think problems 1 and 2 are caused by the same phenomenon.

Question 1 is that if you press Enter to enter the submenu, the Enter is pressed again before you even select Korea or the United States or the United Kingdom or France.

For question 2, when you press Enter to return for the first time, it seems that Question 1 is selected because the Enter is pressed once more even before you select Question 1 or Question 2.

Try calling fflush() before the input function. It seems that the phenomenon occurs because there is an enter left in the input stream. (Or use a function that initializes another input stream)

Thank you.


2022-09-22 19:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.