簡體   English   中英

如何着色 std::cout 的輸出流,而不是 std::cerr 和 std::clog 的輸出流?

[英]How to color the output stream of std::cout, but not of std::cerr and std::clog?

我正在處理以下問題:我在 Ubuntu 上,如果我將所有流塗成紅色,例如使用以下命令:

#include <iostream>

std::cout << "\033[31m" << "From now on the stream is red!";

從現在開始,不僅std::cout對象,而且std::cerrstd::clog對象都將顯示紅色字符串。

我想知道是否有一種方法可以只為std::cout輸出着色並讓std::cerrstd::clog輸出保持不變,從而能夠做到:

#include <iostream>

std::cout << "\033[31m" << "From now on the std::cout stream is red!"; // red stream
std::cerr << "This stream is NOT red"; // normal stream (not colored)
std::clog << "This stream is NOT red"; // normal stream (not colored)

我需要的是一個“設置”(函數、類等),能夠在程序開始時解決這個要求,並讓它保持不變直到結束。

我怎樣才能做到這一點?

經過幾天的嘗試,我找到了一個非常適合這個問題的解決方案。 我只是創建了一個函子,能夠直接將更改應用到std::ostream對象,以這種方式使用:

functor( std::cout ) << "Modified output stream";

這樣的實現有點長,可以在這里找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM