从文件 (C++) 输出 ANSI 转义码时出现问题

Problem outputing ANSI escape code from a file (C++)

我正在做一个玩具项目。基本上,它是一组 classes 和函数,用于制作在终端中 运行 的游戏。我想使用 ANSI 转义码来更改文本颜色、样式、背景颜色等。我正在尝试从文本文件中输入形状和颜色。我将它们存储在 class 中,其中包含一个字符串数组(用于形状)和一个二维字符串数组(用于颜色)。当我对颜色进行硬编码时它工作正常,但是当我从文件中输入它们时(使用 ifstream)它只输出代码而不对文本样式做任何事情。

有没有办法在不编写单独的函数来处理输入代码的情况下解决这个问题?

加载函数:

void charbox::load(std::string path, std::string path2) {
    std::ifstream txt;
    std::string s;
    
    txt.open(path);
    if (txt.is_open() == 0) {
        std::cout << "ERROR 404, " << path << " NOT FOUND!\n";
    }

    while (std::getline(txt,s)) {
        frame.push_back(s);
    }
    txt.close();
        
    txt.open(path2);
    if (txt.is_open() == 0) {
        std::cout << "ERROR 404, " << path2 << " NOT FOUND!\n";
    }
    
    std::vector <std::string> v(frame[0].size(), ""); 
    color.resize(frame.size(), v);
    
    for (int i = 0, height = frame.size(); i < height; i++) {
        for (int j = 0, width = frame[i].size(); j < width; j++) {
            txt >> color[i][j];
        }
    }
    txt.close();
    
}

class:

class charbox {
    public:
                
        std::vector <std::string> frame;
        std::vector <std::vector <std::string>> color;

        void load(std::string path, std::string path2);
        charbox(int p_width, int p_height);
        charbox(){};
    
    private:
};

当我输出:

std::cout << <some object>.color[<some index>][<some index>] << "test\n";

我想根据输入改变“测试”的颜色,但它只是以纯文本形式输出代码。

路径和路径2中的文件示例:

路径包含:

[][]
[][]

路径 2 包含:

3[1;31;41m 3[1;31;41m 3[1;31;41m 3[1;31;41m
3[1;31;41m 3[1;31;41m 3[1;31;41m 3[1;31;41m

提前致谢!

P.S。我正在 运行宁 Linux(windows-特定的解决方案对我不起作用)。

问题在于您对转义序列的解释。如果您在字符串文字中写入 3,那么它将被解释为转义字符 (ASCII 27)。所以

std::string seq = "3[1;31;41m";

个字符的字符串,因为 编译器 3 解释为单个字符。

但是如果你把相同的token放在一个文件中读取它就没有特殊的解释,它会被理解为以反斜杠开头的十三个字符,而不是以转义开头的十个字符。

我建议您编写代码,用转义字符替换 3 序列。像这样

{
    txt >> color[i][j];
    size_t pos = color[i][j].find("\033");  // look for 3
    if (pos != std::string::npos)            // if found
        color[i][j].replace(pos, 4, "3"); // replace with ESC
}

非常重要

查找中的双反斜杠 \ 和替换中的单反斜杠 \