使用ncurses / c ++在同一行中以不同颜色属性打印字符

时间:2019-07-19 22:08:40

标签: c++ linux colors attributes ncurses

我想使用ncurses以与字符串其余部分不同的颜色(具有粗体属性)打印字符。 我只有一个盒子形状,而不是彩色字符。

使用g ++进行编译:

g++ -Wall -std=c++11 print.cpp -lncursesw -o print && ./print

我要使用粗体属性以其他颜色打印的字符是std::string arrow = "\ue0b1";

#define _POSIX_SOURCE
#include <ncurses.h>
#include <string>

int main()
{
    setlocale(LC_ALL, "");

    initscr(); noecho(); cbreak(); curs_set(0);
    if (has_colors()) {
        use_default_colors();
        init_pair(1, COLOR_WHITE, COLOR_CYAN);
        init_pair(2, -1, COLOR_WHITE);
        init_pair(3, -1, COLOR_CYAN);
        init_pair(4, COLOR_CYAN, -1);
    }
    int y, x;
    getmaxyx(stdscr, y, x);
    WINDOW *win = newwin(y, x, 0, 0);
    keypad(stdscr, true);
    wrefresh(win);
    refresh();

    std::string home = "home ";
    std::string cmake_str = " cmake";
    std::string arrow = "\ue0b1";
    home += arrow + cmake_str;

    std::size_t pos = 0; 
    int ch;
    while (1) {
        mvwprintw(win, 0, 0, "Press <Esc> to end program.");
        for (std::size_t i = 0; i < home.length(); ++i) {
            pos = home.find(arrow);
            if (pos != std::string::npos) {
                attron(COLOR_PAIR(1));
                addch(home[i]);
            }
            move(2, i);
            attroff(COLOR_PAIR(1));
            addch(home[i]);
            refresh();
            wrefresh(win);
        }
        if ((ch = wgetch(win)) == 27) { break; }
    }
    delwin(win);
    endwin(); 
    return 0;
}

使用ANSI的预期结果最好是这样的

#include <iostream>
#include <string>
int main()
{
    std::string home = "home ";
    std::string cmake_str = " cmake";
    std::string arrow = "\ue0b1";

    std::string fg_cyan = "\033[36m";
    std::string reset = "\033[0m";
    std::string bold = "\033[1m";

    std::cout << home << bold << fg_cyan << arrow << reset << cmake_str << "\n";
    return 0;
}

0 个答案:

没有答案