【问题标题】:C++ Multiple Choice with Arrow Keys [closed]带箭头键的 C++ 多项选择 [关闭]
【发布时间】:2018-12-26 20:20:53
【问题描述】:

我想知道如何在控制台中进行多项选择提示,您可以在其中使用箭头键选择选项。所以不要像这样:

#include <iostream>
#include <string>

int main()
{
    std::string selection;
    std::cout << "A. option 1";
    std::cout << "B. option 2";
    std::cin >> selection;

    if(selection == "A") {
        //do whatever;
    } else if(selection == "B") {
        //do something else;
    } else {
        //repeat the prompt
    }
return 0;
}

我可以有一些看起来像这样的东西,但没有花哨的 UI: image

【问题讨论】:

  • 好吧,我不认为你可以用cin 或任何标准的东西。这个“花哨的 UI”似乎是 ncurses;您可以将它用于您的程序。
  • 是的,从图片上看是ncurses。您不想自己基于iostream 设施以可移植的方式实现这些东西。

标签: c++


【解决方案1】:

这绝不是一个包罗万象的答案,但我希望它能对基本概念有所帮助。

我编写了一个快速的 C++ 程序,它只使用向上箭头、向下箭头和回车键来执行多选选择器的逻辑部分。

#include <iostream>
#include <conio.h>//For _getch().

//https://stackoverflow.com/questions/24708700/c-detect-when-user-presses-arrow-key
#define KEY_UP 72       //Up arrow character
#define KEY_DOWN 80    //Down arrow character
#define KEY_ENTER '\r'//Enter key charatcer

int main(){
    int selected = 0;    //Keeps track of which option is selected.
    int numChoices = 2; //The number of choices we have.
    bool selecting = true;//True if we are still waiting for the user to press enter.
    bool updated = false;//True if the selected value has just been updated.

    //Output options
    std::cout << "A. Option 1\n"; 
    std::cout << "B. Option 2\n";

    char c; //Store c outside of loop for efficiency.
    while (selecting) { //As long as we are selecting...
        switch ((c = _getch())) { //Check value of the last inputed character.
            case KEY_UP:
                if (selected > 0) { //Dont decrement if we are at the first option.
                    --selected;
                    updated = true;
                }
                break;
            case KEY_DOWN:
                if (selected < numChoices - 1) { //Dont increment if we are at the last option.
                    ++selected;
                    updated = true;
                }
                break;
            case KEY_ENTER:
                //We are done selecting the option.
                selecting = false;
                break;
            default: break;
        }
        if (updated) { //Lets us know what the currently selected value is.
            std::cout << "Option " << (selected + 1) << " is selected.\n";
            updated = false;
        }
    }
    //Lets us know what we ended up selecting.
    std::cout << "Selected " << (selected + 1) << '\n';
    return 0;
}

我使用this 堆栈溢出答案来确定如何跟踪控制台中的按键。 This 答案也可能对在更改文本背景颜色时移动控制台光标很有用。

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多