Boost logo

Boost :

From: jean-thierry lapresté (lapreste_at_[hidden])
Date: 2007-02-07 02:52:50


hello,
 
I would like to be able to recycle boost format in a Matlab(tm) way to output
vectors or lists. I also think it could be valuable to know the number of
elements that can be fed to a given format string.

If it worked the sample code provided at the end of this mail that use a
format for 2 doubles would produce the following output on a vector
containing twelve doubles :

A-> 0 B-> 0.5
A-> 1 B-> 1.5
A-> 2 B-> 2.5
A-> 3 B-> 3.5
A-> 4 B-> 4.5
A-> 5 B-> 5.5

Alas, there is no public method num_args() in the basic_format class...

 ---- What I propose

 The only feature needed in format to make the code work is to be able to
 access the number of arguments expected after the format parsing,
 i.e. an accessor to the private field num_args_ of class
 basic_format which is defined in format_class.hpp.

 I propose to add around line 84 of format_class.hpp the code:

 int num_args() const { return num_args_; }

 I don't think it can it be harmful. Thank you for telling me if I am wrong
 or if there is an other way to do what I mean without modifying anything.

 It's my first post on this list. Please be sure to tell me if my suggestion
is not posted at the proper place.

  Thanks
                   JT Lapresté
 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// sample code begin
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <vector>
#include <boost/format.hpp>

using namespace std;

std::string recycle_format(const std::string & fstr, vector < double > &a)
{
  using namespace boost::io;
  boost::format f(fstr);
  f.exceptions( all_error_bits ^ too_few_args_bit );
  size_t l = f.num_args(), ii = 0;
  std::string s;
  for(size_t i=0; i < a.size(); i++)
    {
      f = f %a[i];
      ii++;
      if(!(ii%l)) {
        ii = 0;
        s += f.str();
        f.clear();
      }
    }
  if((ii%l)) s+= f.str();
  return s;
}

int main()
{
  vector < double > a;
   for(size_t i=0; i < 12; i++) a.push_back(i/2.0);
  cout << recycle_format("A-> %1.0f B-> %3.1f\n", a) << endl;
  return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// code end
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk