【问题标题】:Gnome Terminal cannot print the red color in a program using cursesGnome 终端无法在使用 curses 的程序中打印红色
【发布时间】:2015-06-12 16:39:28
【问题描述】:

我正在尝试进入 ncurses 库。我对 Gnome 终端可以通过 ANSI 转义字符打印红色而不是 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;
}

这应该以任何默认 ncurses 颜色打印单词“color”,但第二行(init_pair 应该将第二个 COLOR_PAIR 初始化为 red ) 根本不打印。似乎 Gnome 终端只是跳过了这一行。我该如何解决这个问题?

【问题讨论】:

  • 可以打印其他颜色吗?还是只是红色失败了?
  • @MooingDuck 我可以毫无问题地打印任何其他预定义颜色:包括黑色、绿色、黄色、蓝色、洋红色、青色和白色。
  • 这可能是本地问题或您的gnome-terminal 中的设置。它适用于 3.14.2。

标签: c ubuntu terminal ncurses gnome


【解决方案1】:

这是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();
}

注意事项

  • 您需要在initscr() 之后调用start_color() 才能使用颜色。
  • 你必须使用COLOR_PAIR
  • 将分配给init_pair 的颜色对传递给attron 等。
  • 您不能使用颜色对 0。
  • 您只需拨打refresh()一次,
  • 且仅当您希望在该点看到您的输出时,
  • 并且您没有调用像 getch() 这样的输入函数。

【讨论】:

  • 我在这里看不到任何不在 OP 中的步骤
  • OP 的程序正常运行;一个有用的答案是评论一些颜色主题的怪癖,或者提到一个已知的错误(来自错误报告)。后者一个都没有想到,前者的想象力不够。
猜你喜欢
  • 1970-01-01
  • 2016-04-12
  • 2011-09-28
  • 2018-04-17
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多