原始問題是:如何在發生換行符後自動插入某些內容到流中。插入應該只在事後插入(手動)插入流時纔會發生。C++ Stream:在換行符後面插入字符串
以下是更詳細的解釋。
對於練習我正在寫自己的記錄器類。基本的日誌記錄功能由這段代碼給出。
class Logger {
public:
static std::ostream & log(LogLevels::LogLevel level);
};
// Use it:
Logger::log(LogLevels::WARNING) << "Something serious happened!" << std::endl;
的示例打印像
[ WARNING: 0 ] Something serious happened!
我想延長這一功能,使得一個新行插入流之後所有調試消息由記錄頭的寬度縮進直到Logger::log
再次被調用。
// Example (1)
Logger::log(LogLevels::WARNING) << "Something happened!"
<< std::endl
<< "Some More information: "
<< 42
<< " (Still on the same line)"
<< std::endl;
Logger::log(LogLevels::INFO) << "Merely a status code"
<< std::endl
<< "Which reads: "
<< 21
<< " (Also on the same line)"
<< std::endl;
// Example (2)
std::ostream & os = Logger::log(LogLevels::WARNING);
os << "First line"
<< std::endl;
os << "Second line"
<< std::endl;
// Example (3)
// [...]
// Some code is executed
Logger::log(LogLevels::WARNING) << "A new error"
<< std::endl
<< "The code strikes back"
<< std::endl
<< "The return of the bugs"
<< std::endl ;
這將產生:
[ WARNING: 0 ] Something hapened! Some More information: 42 (Still on the same line) [ INFO: 1 ] Merely a status code Which reads: 21 (Also on the same line) [ WARNING: 2 ] First line Second line // [...] [ WARNING: 99998 ] A new error The code strikes back The return of the bugs
這種行爲可以實現,如果是這樣,這是如何最好地展示一個例子來說明?
http://kuhllib.com/2012/01/14/stop-excessive-use-of-stdendl/ – BoBTFish
這似乎不是一個非常直觀的界面。 –
@BoBTFish's/std :: endl /'\ n'/ g'我的問題不是關於使用'std :: endl',我很清楚速度的不同。不過,我認爲在例子中使用'std :: endl'這樣的代碼使得它更具可讀性。 – elemakil