带有箭头键的C ++多项选择

时间:2018-07-18 19:54:09

标签: c++

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

rawData = [{
    x: 1,
    y1:"1 y1 string", 
    y2:"1 y2 string",
    y3:"1 y3 string",

    yn:"1 yn string",
},{
    x: 2,
    y1:"2 y1 string", 
    y2:"2 y2 string",
    y3:"2 y3 string",

    yn:"2 yn string",
}];

  convertedData = [
    {
      name:"y1",
      data:[
        [1,"1 y1 string"],
        [2,"2 y1 string"],
      ]
    },{
      name:"y2",
      data:[
        [1,"1 y2 string"],
        [2,"2 y2 string"],
      ]
    },{
      name:"y3",
      data:[
        [1,"1 y3 string"],
        [2,"2 y3 string"],
      ]
    },{
      name:"yn",
      data:[
        [1,"1 yn string"],
        [2,"2 yn string"],
      ]
    }
  ];

我可能会有类似以下的内容,但没有精美的UI: image

1 个答案:

答案 0 :(得分:1)

这绝不是一个全面的答案,但我希望它能对基本思想有所帮助。

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

#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答案也可能在更改文本的背景色时对于移动控制台光标很有用。

祝你好运!

相关问题