防止 NCurses C++ 库创建子窗口

问题描述 投票:0回答:1

我想阻止 C++ ncurses 库在激活时创建自己的子窗口。每当您将

initscr()
与 ncurses 一起使用时,它都会创建自己的子窗口(终端中的文本区域)。不使用
initscr()
并继续使用 ncurses 将导致分段错误。有谁知道如何使用 ncurses 而不创建自己的子窗口?

在我的例子中,我使用 ncurses 来执行“选择提示”,其中显示选项,用户可以使用箭头键浏览它们,直到找到他们想要的选项(输入两次键进行选择)。

#include <iostream>
#include <vector>
#include <string>
#include <ncurses.h>

std::string prompt(const std::vector<std::string> &options, const std::string &message)
{
    // * NCURSES init
    initscr();
    cbreak();
    keypad(stdscr, true);
    noecho();

    int choice;
    int highlight = 0;
    int num_options = options.size();

    while (true)
    {
        // * Clear line
        int y, x;
        getyx(stdscr, y, x);
        move(y, 0);
        clrtoeol();

        // * Display options
        printw("%s: ", (message).c_str());
        for (int i = 0; i < num_options; ++i)
        {
            if (i == highlight)
                attron(A_REVERSE);

            printw("%s ", options[i].c_str());
            attroff(A_REVERSE);
        }

        // * Get user input
        choice = getch();

        // * Decoding selection
        switch (choice)
        {
        case KEY_RIGHT:
            highlight = (highlight - 1 + num_options) % num_options;
            break;
        case KEY_LEFT:
            highlight = (highlight + 1) % num_options;
            break;
        case '\n':
            refresh();
            getch();
            endwin();
            printf("\n");
            return options[highlight];
        default:
            break;
        }
    }

    // * NCURSES cleanup
    refresh();
    getch();
    endwin();
}

int main()
{
    std::cout << "Hello World!\n";
    prompt({"agree", "disagree"}, "choose one");
    std::cout << "Hello World #2\n";

    return 0;
}

如果你运行这段代码,你会注意到在ncurses子窗口中,只会出现提示功能中的内容。选择后,您将看到第一条消息(“Hello World”),然后是提示所在的空行,然后是第二条消息(“Hello World #2”)。

c++ segmentation-fault prompt ncurses curses
1个回答
0
投票

Ncurses 如果不使用它自己的子窗口就无法工作。

© www.soinside.com 2019 - 2024. All rights reserved.