Search code examples
cncursescurses

Continuous keyboard input with Curses in C saving string and history of N lines


I was wondering if anyone would know how I can modify the following code to allow me to wait for a text entry to be entered, to store it in the corresponding variable and to jump to the next line immediately below it without deleting what was written before except when the size of the window created is exceeded.

#include <curses.h>

int main()
{
    WINDOW *wnd;
    char txt[100];
    // INICIALIZACIÓN DE LAS VENTANAS.
    initscr();
    cbreak();
    noecho();
    refresh();
    start_color();
    init_pair(1,COLOR_WHITE,COLOR_RED);

    wnd = newwin(10,100,1,1);
    wattron(wnd,COLOR_PAIR(1));
    wbkgd(wnd,COLOR_PAIR(1) | ' ');
    wclear(wnd);
    box(wnd,ACS_VLINE,ACS_HLINE);

    wmove(wnd,1,1);
    wprintw(wnd,">> ");
    wrefresh(wnd);
    wmove(wnd,1,6);
    echo();
    wgetstr(wnd,txt);
    noecho();

    return 0;
}

What I have programmed right now as soon as it detects the first intro stores the value in char but closes the ncurses window...

Does anyone know how I can fix it to get what I'm looking for?


Solution

  • Are you speaking about scrolling the window when the cursor is at the the bottom of the window ?

    #include <ncurses.h> // <-------------- I use ncurses
    
    int main()
    {
      WINDOW *wnd;
      char txt[100];
      int  line;
    
      // INICIALIZACIÓN DE LAS VENTANAS.
      initscr();
      cbreak();
      noecho();
      refresh();
      start_color();
      init_pair(1,COLOR_WHITE,COLOR_RED);
    
      wnd = newwin(10,100,1,1);
      scrollok(wnd, TRUE);       // <--------- Allow scrolling
      wattron(wnd,COLOR_PAIR(1));
      wbkgd(wnd,COLOR_PAIR(1) | ' ');
      wclear(wnd);
      box(wnd,ACS_VLINE,ACS_HLINE);
    
      line = 1; // <------------- First line in the window
    
      while (1) {
    
        wmove(wnd,line,1);
        wprintw(wnd,">> ");
        wnoutrefresh(wnd);
        doupdate(); // <----- Refresh all the preceding modifications
        echo();
        wgetstr(wnd,txt);
        noecho();
        if (line < 8) {  // <------- Check bottom of window
          line ++;
        } else {
          box(wnd,COLOR_PAIR(1) | ' ', COLOR_PAIR(1) | ' '); // <--- Clear old box before scrolling
          wscrl(wnd, 1); // <------ scroll 1 line up
          box(wnd,ACS_VLINE,ACS_HLINE); // <------ Redo the box
        }
      }
    
      endwin();
    
      return 0;
    }