Search code examples
cncurses

How to avoid rewriting the pieces of text that don't change


I have developed a simple NCurses application that I use for debugging purposes. It constantly prints and updates some variables and their values on a terminal window.

I'm using the printw function to print the variable names and their values like this:

while( ... )
{
    clear();

    printw("var_1: %d\n", var_1);
    printw("var_2: %d\n", var_2);
    printw("var_3: %d\n", var_3);
    ...

    refresh();
}

This produces an output like this:

var_1: 10
var_2: 20
var_3: 30
...

Since this piece of code is inside a loop, I'm constantly rewriting the entire screen, both the variable names and their values.

Notice that the only data that needs to be updated are the values, as the variable names are always the same, so there's no need to re-write them over and over on every iteration.

How can I to avoid rewriting the pieces of text that don't change in my NCurses application?


Solution

  • With NCurses, your screen area is just a two dimensional grid. You can print at any position of the screen with mvprintw()

    So first print the fixed text a a given position, then, in your loop, print the value at the corresponding value position:

    mvprintw( x, y,   "var_1:" );
    mvprintw( x, y+1, "var_2:" );
    while( ... )
    {
    /// compute values
       mvprintw( x+6, y,   value1 );
       mvprintw( x+6, y+1, value2 );
    }
    

    Reference