Re: [C++] ostrstream vs. sprintf

From: Daniel A. Koepke (dkoepke@circlemud.org)
Date: 02/05/02


On Tue, 5 Feb 2002, Karl B Buchner wrote:

> I was looking through some C++ documentation, and I noticed the
> ostrstream class (heretofor unbeknownst to me).

strstring is deprecated.  Its replacement within the IOStreams framework
is stringstream.  A standard example would be:

  #include <iostream>
  #include <sstream>  // stringstream lives here

  int
  main ()
  {
      std::stringstream ss;
      std::string str;
      double d = 3.1415;
      ss << d;
      ss >> str;
      std::cout << "As a double: " << d << '\n'
                << "As a string: " << str << std::endl;
  }


>         -no need for messy %-5ld type stuff
>

The equivalent in Standard C++ isn't necessarily cleaner:

  oss << std::left << std::setw(5) << foobar;


> one disadvantage that I noticed was cases where you want to set the
> size of the parameter (i.e. %20s).

You probably meant "%.20s", which sets the string's "precision" (length),
not "%20s", which right-justifies it in a field of 20 spaces.  Note that
these are quite different, as "%20s" will still print all of a string,
regardless of its length.  "%.20s" performs the intended truncation.

For C++, you might consider migrating to std::string, in which case you
can handle this explicitly with the substr() member, like:

  std::string str = ...;     // Set to some string.
  oss << str.substr(0, 20);  // first 20 characters only.


-dak

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   | Newbie List:  http://groups.yahoo.com/group/circle-newbies/   |
   +---------------------------------------------------------------+



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