0
votes

I am trying to get into the ncurses library. I am dissapointed that the Gnome Terminal can print red via ANSI escape characters but not the predefined red from ncurses.

#include <curses.h>

void init_colors() {
    int a;
    for(a = 1; a < COLORS; a++) {
        init_pair(a, a, COLOR_BLACK);
    }
}

void print_colors() {
    int a;
    for(a = 1; a < COLORS; a++) {
        attron(COLOR_PAIR(a));
        mvprintw(a, 0, "color");
        attroff(COLOR_PAIR(a));
    }
}

int main() {
    initscr();
    cbreak();
    noecho();
    curs_set(0);

    if(has_colors()) 
        start_color();          

    init_colors();
    print_colors();
    getch();
    endwin();

    return 0;
}

This should print the word "color" in any default ncurses color, but the second line (init_pair should initialize the second COLOR_PAIR as red) is not printed at all. It seems that Gnome Terminal simply skip this line. How can I fix this?

1
Can you print any other colors? Or is it just red that fails? - Mooing Duck
@MooingDuck I can print any other of the predefined colors without problems: Including black, green, yellow, blue, magenta, cyan and white. - Markus
This could be a local issue or setting in your gnome-terminal. It works here with 3.14.2. - gpoo

1 Answers

-2
votes

This is a copy of another stackoverflow answer

#include <curses.h>

int main(void) {
    initscr();
    start_color();

    init_pair(1, COLOR_BLACK, COLOR_RED);
    init_pair(2, COLOR_BLACK, COLOR_GREEN);

    attron(COLOR_PAIR(1));
    printw("This should be printed in black with a red background!\n");

    attron(COLOR_PAIR(2));
    printw("And this in a green background!\n");
    refresh();

    getch();

    endwin();
}

Notes

  • you need to call start_color() after initscr() to use color.
  • you have to use the COLOR_PAIR macro
  • to pass a color pair allocated with init_pair to attron et al.
  • you can't use the color pair 0.
  • you only have to call refresh() once,
  • and only if you want your output to be seen at that point,
  • and you're not calling an input function like getch().