c++segmentation-faultpromptncursescurses

Prevent NCurses C++ Library From Creating Sub-Window


I want to prevent the C++ ncurses library from creating its own sub-window when activated. Whenever you use initscr() with ncurses, it creates its own sub-window (text area in terminal). Not using initscr() and proceeding to use ncurses will lead to a segmentation fault. Does anyone know how to use ncurses without it creating its own sub-window?

In my case I am using ncurses to do a "selection prompt" where options are displayed, and the user can go though them with arrow keys until the find one they want (enter key twice to select).

#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;
}

If you run this code, you will notice that in the ncurses sub window, only the stuff in the prompt function will appear. After selection, you will see the first message ("Hello World"), then a blank line where the prompt should be, then the second message ("Hello World #2").


Solution

  • Ncurses does not work without using it's own sub-window.