Main Page   Modules   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members   File Members   Related Pages   Examples  

Using CTBprintf

Introduction

The CTBprintf format objects allow to output formatted representations of elementary types on C++ streams with almost the same compactness as with the C call printf but without loosing a type-safe interface. The format objects take care of all the stream setup, output the number, and restore the original stream state.

Why worry to learn yet another thing ?

Consider the following example: to output an integer in hexadecimal notation with a leading "0x", with 8 digits and zero-fill one just writes

    cout << CTBprintf(iii,"$x0",10);
Compare this to the equivalent code using only the functionality provided by the C++ stream classes:
    cout.setf(ios::showbase);
    cout.setf(ios::internal);
    cout << setfill('0') << setbase(16) << setw(10) << iii;
The above example actually leaves the stream in a state different from the default state (integers are from now on formated hex rather decimal), which very often creates havoc in output created later on. So one better saves the stream state an restores it later, which results for our example in a code like
    long flags = cout.flags();
    char fill  = cout.fill();
    cout.setf(ios::showbase);
    cout.setf(ios::internal);
    cout << setfill('0') << setbase(16) << setw(10) << iii;
    cout.flags(flags);
    cout.fill(fill);
A lot of coding for getting a single number into a stream.

Format control

All variants of CTBprintf() calls take at least three arguments:

The way the number is formatted is controlled by the c_format string and the additional i_width and i_precision parameters which control the field width and the way floating point numbers are formatted. The format string has the following simple form
       [<modifiers>]<conversion_type>[<fill_character>]
The list of modifiers can contain the letters (in any order)
+ show + sign for positive numbers
- print field left justified
. always show decimal point
$ indicate base (precede with 0 or 0x for octal/hex)

The conversion type should be one of
d decimal conversion
o octal conversion
x hexadecimal conversion
g generic floating format
f fixed point floating format
e scientific floating format
p pointer format
c print int as char
s print string

The x, g, and e conversion types can also be specified in upper case. This will cause an uppercase "0X" prefix or an uppercase "E" exponent delimiter.

Any character after the conversion type is treated as fill character. If none is given blanks will be used.


Generated at Fri Oct 24 18:14:16 2003 for CTBbase by doxygen1.2.9-20010812 written by Dimitri van Heesch, © 1997-2001