c++ - 使用 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;
}
解决方案
推荐阅读
- ios - 使用 ReplayKit 广播时将 CMSampleBuffer 转换为 .mov
- here-api - “这些凭据不授权访问”(403)
- pyspark - Pyspark,如何使用udf计算泊松分布?
- php - Google 访问令牌不会在离线访问时自动刷新
- python - docker:来自守护进程的错误响应:OCI 运行时创建失败:没有这样的文件或目录”:未知
- build - Fortran 新手:如何在 Geany 中编译/构建多个 Fortran 文件
- python - 无法在 django 中编写动态元标记
- java - Apache POI - 饼图 - java.lang.IllegalStateException:类别和值必须具有相同的点数
- python - 无法将“版本”解析为有效参考。运行 git 标签时
- python - 如何将带注释的查询限制为 Django ORM 中的单个列?