添加“提示”的最佳方式消息到std :: cout [英] Best way to add a "prompt" message to std::cout
本文介绍了添加“提示”的最佳方式消息到std :: cout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在搜寻向 std :: cout
(或 std ::)的所有邮件添加自定义的初始消息的最佳方法
I'm searching the best way to add a custom, initial message to all the messages that std::cout
(or std::cerr
) prints to console/file output.
例如,如果我设置这个自定义提示消息将是字符串[Log] ,然后是经典
For example, if I setup that this custom prompt message will be the string "[Log]", then a classic
std::cerr << "This is a log message" << std::endl;
将以这种方式打印:
> [Log] This is a log message
显然,我可以使用
std::string PROMPT_MSG = "[Log]";
std::cerr << PROMPT_MSG << "This is a log message" << std::endl;
但我想要一种侵入性较小的方法。
but I'd like a less invasive way.
提前感谢
推荐答案
您可以编写自己的类:
#include <iostream>
#include <string>
class MyLogger
{
std::ostream & out;
std::string const msg;
public:
MyLogger(std::ostream & o, std::string s)
: out(o)
, msg(std::move(s))
{ }
template <typename T>
std::ostream & operator<<(T const & x)
{
return out << msg << x;
}
};
MyLogger MyErr(std::cerr, "[LOG] ");
用法:
MyErr << "Hello" << std::endl;
这篇关于添加“提示”的最佳方式消息到std :: cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文