2014-09-23 79 views
0

我正在使用ANSI颜色代码在Unix控制台中格式化我的输出。处理iostream操纵器和ANSI控制台颜色代码

const auto& getCode(Color mColor) 
{ 
    static std::map<Color, std::string> codes; 
    // ... 
    return codes[mColor] 
} 

cout << getCode(Color::Red) << "red text"; 

当使用操纵器如std::setwstd::left,然而,结果由颜色代码受影响,因为它是一串字符。

我应该如何处理这个问题?有没有办法让流操纵器忽略颜色代码?

+0

你的意思是将它们通过改变但不影响什么吗? 'getCode'的定义是什么? – Deduplicator 2014-09-23 13:17:44

+0

你的函数是否返回i​​nt或char?请与我们分享getCode原型。 – 2014-09-23 13:18:52

+0

getCode是一个输出流操作符的结构吗?也许你有兴趣设置和恢复iostream标志:http://stackoverflow.com/questions/4217704/roll-back-or-undo-any-manipulators-applied-to-a-stream-without-knowing-what-th – Sven 2014-09-23 13:32:27

回答

4

getCode返回的是什么类型?如果它不是 std::stringchar const*,您只需要为其编写 a <<,它忽略了您不希望 影响的格式化数据。如果是C++的字符串类型中的一种,那么你 也许应该换一个特殊对象的号召,与<< 该对象类型,例如:

class ColorCode 
{ 
    ColorType myColor; 
public: 
    ColorCode(ColorType color) : myColor(color) {} 
    friend std::ostream& operator<<(std::ostream& dest, ColorCode const& cc) 
    { 
     std::string escapeSequence = getCode(myColor); 
     for (char ch : escapeSequence) { 
      dest.put(ch); 
     } 
     return dest; 
    } 
}; 
+0

我怀疑它返回'“\ x1B [41m”'。我同意你的想法更好,你可以只写'cout << Color :: Red <<“红色文字”;' – MSalters 2014-09-23 14:24:33

+0

非常感谢!它非常简单。我已经在测试一个对格式化字符串和颜色代码进行排序的缓存流的实现......结果你只需要一个简单的包装类! – 2014-09-23 14:58:43