|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionWhile I was writing this article, I saw that a fellow CP'ian, Ivo Beltchev, has already posted a typesafe string format library. The method I used in my library is quite similar to his. But my library is much simpler, and uses Here is an example of the usage: using namespace strfmt;
std::wstring szHello = L"Hello";
std::wcout<< StrFormat( L"{0}, {0}, I am {1}",
szHello, 22.0 ) << std::endl;
The output is as below: Hello, Hello, I am 22.000000
Source codeThis is the function declaration, with a constant string and two arguments: std::wstring strfmt::StrFormatW(
const wchar_t* fmt,
strfmt::BoxW box1,
strfmt::BoxW box2 );
Let us see its definition, which is surprisingly simple: std::wstring strfmt::StrFormatW(
const wchar_t* fmt,
strfmt::BoxW box1,
strfmt::BoxW box2 )
{
std::wstring wsfmtstr = fmt;
std::vector<std::wstring> vs;
vs.push_back( box1.ToString() );
vs.push_back( box2.ToString() );
return StrReplaceW( wsfmtstr, vs );
}
Let us see the class declaration of class BoxW
{
public:
BoxW( int i );
BoxW( unsigned int ui );
BoxW( const __int64& i64 );
BoxW( const unsigned __int64& ui64 );
BoxW( float f );
BoxW( const double& d );
BoxW( const std::string& s );
BoxW( const std::wstring& ws );
BoxW( const char* pc );
BoxW( const wchar_t* pwc );
BoxW( char c );
BoxW( wchar_t wc );
std::wstring& ToString() { return m_str; }
protected:
std::wstring m_str;
};
The class consists of 12 non-default constructors, and a method, There is also an ASCII version of the class, which is used depending on whether ##ifdef _UNICODE
#define StrFormat StrFormatW
#define Hex HexW
#define Oct OctW
#define Bin BinW
#define Sci SciW
#define Flt FltW
#else
#define StrFormat StrFormatA
#define Hex HexA
#define Oct OctA
#define Bin BinA
#define Sci SciA
#define Flt FltA
#endif
In order to keep the library simple, the paradigm used is different from the .NET string format, the numbers formatting is kept outside. std::wcout<< StrFormat( L"{0}, {1}, {2}",
Hex( 255 ), Sci( 22.0 ), Flt( 22.0, 3 ) ) << std::endl;
The output is as below: ff, 2.200000e+001, 22.000
Supporting your own typeJust add a method (example, using namespace strfmt;
MyClass myclass;
std::cout<< StrFormat( "{0} {1}",
myclass.ToString(), 22.0 ) << std::endl;
ConclusionThis string format library is designed from ground up, that it is so simple that any user can edit/add features himself/herself easily. If you compile the source code in Visual C++ 8 or Visual Studio 2005, it uses the new Safe C functions. History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||