0

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?

gpoo
  • 8,408
  • 3
  • 38
  • 53
Markus
  • 93
  • 6
  • Can you print any other colors? Or is it just red that fails? – Mooing Duck Apr 08 '15 at 00:19
  • @MooingDuck I can print any other of the predefined colors without problems: Including black, green, yellow, blue, magenta, cyan and white. – Markus Apr 08 '15 at 07:19
  • This could be a local issue or setting in your `gnome-terminal`. It works here with 3.14.2. – gpoo Apr 15 '15 at 22:21

1 Answers1

-2

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().
Community
  • 1
  • 1
user3629249
  • 16,402
  • 1
  • 16
  • 17
  • I can't really see any steps here that aren't in the OP – Mooing Duck Apr 08 '15 at 00:21
  • 1
    The OP's program worked correctly as such; a useful answer would either comment on some quirk of color themes, or mention a known bug (from bug reports). None of the latter come to mind, imagination isn't sufficient for the former. – Thomas Dickey Apr 08 '15 at 00:31