gpt4 book ai didi

c++ - 如何将 printf xterm 代码转换为 ostringstream?

转载 作者:太空宇宙 更新时间:2023-11-04 03:55:22 24 4
gpt4 key购买 nike

问题

我正在尝试将一些 C printf 代码转换为 std::ostringstream,但我在十六进制/终端编码方面遇到了问题。我想也许序列 \x1b[48;5; 需要立即翻译,但我不确定 C++ 中的等价物是什么。

错误结果,部分 (C++)

Color cube, 6x6x6:
1b[48;5;10m 1b[48;5;10m 1b[48;5;11m 1b[48;5;11m 1b[48;5;12m 1b[48;5;12m 1b[48;5;13m 1b[48;5;13m 1b[48;5;14m 1b[48;5;14m 1b[48;5;15m 1b[48;5;15m 1b[0m 1b[48;5;34m 1b[48;5;34m 1b[48;5;35m

良好的结果,xterm (C)

enter image description here

C代码

void Color_Cube()
{
for (unsigned green=0; green<6; ++green)
{
for (unsigned red=0; red<6; ++red)
{
for (unsigned blue=0; blue<6; ++blue)
{
unsigned color = 16 + (red * 36) + (green * 6) + blue;
printf( "\x1b[48;5;%dm ", color );
}
printf( "\x1b[0m " );
}
printf( "\n" );
}
}

失败的 C++ 代码

void Color_Cube_cpp()
{
std::ostringstream oss;
for (unsigned green=0; green<6; ++green)
{
for (unsigned red=0; red<6; ++red)
{
for (unsigned blue=0; blue<6; ++blue)
{
unsigned color = 16 + (red * 36) + (green * 6) + blue;
oss << std::hex << static_cast<int>(0x1b) << std::dec
<< "[48;5;" << color << "m ";
}
oss << std::hex << static_cast<int>(0x1b) << std::dec << "[0m ";
}
oss << "\n";
}
std::cerr << oss.str() << "\n";
}

最佳答案

你快到了。您需要流式传输转义字符 '\x1b' 而不是整数 0x1b:

#include <sstream>
#include <iostream>

void Color_Cube_cpp()
{
std::ostringstream oss;
for (unsigned green=0; green<6; ++green)
{
for (unsigned red=0; red<6; ++red)
{
for (unsigned blue=0; blue<6; ++blue)
{
unsigned color = 16 + (red * 36) + (green * 6) + blue;
oss << "\x1b[48;5;" << color << "m ";
}
oss << "\x1b[0m ";
}
oss << "\n";
}
std::cerr << oss.str() << "\n";
}

关于c++ - 如何将 printf xterm 代码转换为 ostringstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16870317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com