Re: [C++] ostrstream vs. sprintf

From: Henrik Stuart (
Date: 02/06/02


>>   As far as I recall I have seen the %20s a few places in the code,
>>   might just be misrememberance. :o)

> $ egrep '%[0-9.]+' *.c | wc -l
>      62

   Guess my memory isn't as bad as I used to think. :o)

> I remember the first time I ever saw 'cout' after sprintf. I was (and still
> am) very unimpressed.

   I won't argue that cout/ostream is nicer to use than the printf
   family, because, imho, it's usually easier to see the construction
   of what you want to output, which isn't always crystal clear when
   you use complex output operations with lots of setw, setprecision,
   etc. manipulators.

   However, the benefit of cout over the printf-family is... type
   safety and overloading. :o)

   Consider this:

   short s = 37;
   int n = 38;
   fprintf(fp, "%d %d", s, n); // fp being a FILE*
   fout << s << ' ' << n; // fout being a std::ofstream

   This is a rather simplistic example since short is automatically
   promoted to int and whatnot, but use your imagination for the more
   complex example. :o)

   However, the iostream capabilities do not come to their full right
   until we look at an example where we want the representation of
   something when written to always be the same - an obvious choice to
   look at as an example would be outputting a matrix:

   std::ostream& operator<<(std::ostream& os, const Matrix& m) {
     for (int i = 0; i < m.rows(); ++i) {
       for (int j = 0; j < m.cols(); ++j) {
         os <<,j) << ", ";
       os << std::endl;
     os << std::endl;
     return os;

   Normally, with a few changes, we would reproduce the double
   for-loop every time we want to print a matrix (the apt pupil would
   most likely wrap this in a few functions) - however, the force in
   the iostream library lies in the inheritance, so with just the
   above code we can do all of this:

   Matrix m<4,4>; // creates a 4x4 matrix
   std::cout << m;
   std::ofstream fout("outfile.txt");
   fout << m;

   We could even send it to char_data (if we make it inherited from an
   ostream), and the representation would still be unchanged.

> My biggest gripe with *printf() is when you have a
> typedef that varies what it is in your format string.  The whole 'need a
> big enough buffer' thing isn't so great but you can use snprintf() to work
> around that because it tells you how much space it needs (unless you're
> using GNU C library 2.0, ick).

   Double ick to that library. :o)

   And it is rather lovely to have std::string, std::stringstream and
   likes at your disposal. :o)

Yours truly,
  Henrik Stuart (

   | FAQ: |
   | Archives: |
   | Newbie List:   |

This archive was generated by hypermail 2b30 : 06/25/03 PDT