Back to Search Start Over

StringPrintf: A Typesafe printf Family for C++.

Authors :
Wörthmüller, Stefan
Source :
C/C++ Users Journal. Aug2005, Vol. 23 Issue 8, p32-37. 4p. 3 Color Photographs.
Publication Year :
2005

Abstract

This article features StringPrintf, a typesafe version of the print function family for C++ program languages. StringPrintf can be used with std::string and with C strings. In addition, it can do everything that sprintf does and is compatible with all standard printf format strings. In fact, internally, it uses sprintf itself. The big difference is that it checks the type character of the format string, choosing instead the type appropriate for the argument supplied. The type character is used for legal conversions and compatibility. I implemented StringPrintf in multiple versions that can replace printf, sprintf, snprintf and fprintf. The implementation of StringPrintf is quite straightforward. I started by creating a small helper class named CPrintfArg, which can hold one value of any built-in data types. Because all StringPrintf functions use the same argument type, it is easy to declare custom conversions for user-defined types. All that is needed is a function that converts a user-defined object to an object of type CPrintfArg. In this implementation, CPrintfArg::Out has certain limitations. For simplicity, everything is passed to sprintf. Therefore, static buffers are used in most cases. Also, the handling of erroneous format strings is different from sprintf, starting with the fact that StringPrintf rejects wrong type characters, up to where sprintf can handle arbitrary string and format lengths that StringPrintf probably cannot handle.

Details

Language :
English
ISSN :
10752838
Volume :
23
Issue :
8
Database :
Academic Search Index
Journal :
C/C++ Users Journal
Publication Type :
Periodical
Accession number :
17660606