告别printf 拥抱 std::cout

本文探讨了C++中使用标准输出流std::cout进行日志输出的方法,避免printf带来的类型错误风险。通过自定义<<操作符,可以轻松输出自定义数据结构,如链表,有效减少bug,提升代码稳定性。

我们使用printf 的时候或者自己构造的printf,有的时候会有这样的烦恼,输出很容易出错,如果 int 类型对应 %s 那么必然要崩溃。为了解决问题结果打log崩溃,是令人很恼火的事。
c++ 的输出或者日志输出
std::cout << “hello” << endl;

c++ 98 实现了如下函数:

arithmetic types (1)
ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);

如果我们要使用 << 输出自己的结构体,那么只需要自己实现 << 操作符即可

std::ostream& operator << (std::ostream& os,std::list<std::string>& lst)
{
	int i = 0;
	for (std::string& var : lst)
	{
		os << "item: " << i++ << " " << var << ",";
	}
	return os;
}

输出一个链表的内容

	std::list<std::string> lst;
	lst.push_back("gaga");
	lst.push_back("lala");
	cout << lst << endl;

自动会少一些bug,烦恼会减少不少.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值