[Effective-cpp] Item 3: The String Formatters of Manor Farm, P art 2

Ric Parkin ric.parkin at ntlworld.com
Tue Nov 2 06:28:20 EST 2004


From: "Hammond, Peter" <peter.hammond at amsjv.com>
> > -----Original Message-----
> > From: Gregory Haley [mailto:ghaley at venaca.com]
> > Sent: 01 November 2004 18:26
> > To: effective-cpp at accu.org
> > Subject: [Effective-cpp] Item 3: The String Formatters of Manor
> > Farm,Part 2
> > 
> > Item 3.  The String Formatters of Manor Farm, Part 2:  Standard (or
> > Blindingly Elegant) Alternatives
> > 
> > type safety and is not useful for templates.  I disagree with 
> > the assertion
> > that sprintf and snprintf code is clear and unambiguous.
> 
> I think the sprintf-style formatters are simpler in many but not all cases.
> Yes I was C programmer before coming to C++. The stream-like formats are not
> too bad when the default format is aceptable, but even then putting in the
> separators can be a pain: compare
> sprintf (buf, "step %d gives %f", n, result);
> with 
> buf << "step " << n << " gives " << result;
> Not too bad and I'd probably go with the latter.
> 
> Where the interter wins is where you have many (whatever that means)
> elements in one go.

Even then it's not really that much better. Where streams *really* win is when you've a loop, or conditionals. Ie they're much better at allowing concatenation.

eg
for ( ...iterate container...)
  {
     out << *i.firstname;
     if ( *i.HasInitial )
       out << ' ' << *i.Initial << ".";
     out << ' ' << *i.lastname;

     out << '\n';
  }
 
> But where to my mind it really falls over is when you have to put in
> formatting. 

Indeed - there are several variants of formatter helpers to avoid some of the mess that can result.

> I agree with the article, all those manipulators get in the way.
> Also I can never remember (a) what they are and (b) which ones are
> persistent and which ones only affect the next insertion, so I have to go to
> the manual. 

Yes, that's a *real* pain. I wish they'd made them *all* sticky, and have a save_and_restore scoped mechanism.

> Not the end of the world, and I'm sure I'd get the hang of them
> eventually. However, I was about to do another comparison when I realised
> that I couldn't remember anything like enough manipulator syntax to do it,
> so I rest my case :).

Ah, but how many times do you have to look up anything non-trivial in the sprintf formatters? 

As an embarrassingly simple example, I still have to double-check when I want to print a long to make sure the "l" goes in the right place. Been bitten by that one getting %dl or doing %l instead of %ld. And I can't be sure I've just got it the right way round. <sigh>

Ric


-----------------------------------------
Email provided by http://www.ntlhome.com/





More information about the Effective-cpp mailing list