游戏log是非常关键的,对于追踪bug和查看一些信息,所以游戏里面是大量的log输出,sprintf的格式非常难用,而且对格式有较高的要求。
下面一种优化方案如下:
// MVC.cpp : 定义控制台应用程序的入口点。
//
// MVC.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class EndLogOut{};
class LogOut
{
public:
LogOut(int type)
{
m_type = type;
}
~LogOut()
{
logString = ss.str();
cout<<logString<<endl;
}
LogOut& operator<<(int a)
{
ss<<a;
return *this;
}
LogOut& operator<<(float a)
{
ss<<a;
return *this;
}
LogOut& operator<<(bool a)
{
ss<<a;
return *this;
}
LogOut& operator<<(char* a)
{
ss<<"."<<a<<".";
return *this;
}
LogOut& operator<<(std::string a)
{
ss<<"."<<a<<".";
return *this;
}
std::string operator<<(std::basic_ostream<char, char_traits<char> >& _Ostr)
{
logString = ss.str();
return logString;
}
std::string operator<<(EndLogOut)
{
logString = ss.str();
cout<<logString<<endl;
return logString;
}
std::string GetString()
{
logString = ss.str();
return logString;
}
private:
ostringstream ss;
std::string logString;
int m_type;
};
#define ELOGOUT LogOut(1)
#define ENGLOG EndLogOut()
int _tmain(int argc, _TCHAR* argv[])
{
//LogOut log;
char* s = "ssss";
std::string ss = "oooo";
float ff = 1.09f;
bool bb = true;
//log<<1<<"test"<<s<<ss<<ff<<bb;
ELOGOUT<<1<<"test"<<s<<ss<<ff<<bb;
//cout<<log.GetString()<<endl;
return 0;
}