首页 > 解决方案 > 使用 ncurses/c++ 在同一行中以不同颜色属性打印字符

问题描述

我想使用 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;
}

标签: c++linuxcolorsattributesncurses

解决方案


推荐阅读