ENH: provide formatting version of Foam::name() (issue #253)

- there are some cases in which the C-style sprintf is much more
  convenient, albeit problematic for buffer overwrites.

  Provide a formatting version of Foam::name() for language
  primitives that is buffer-safe.

  Returns a Foam::word, so that further output will be unquoted, but
  without any checking that the characters are indeed entirely valid
  word characters.

  Example use,
      i = 1234;
      s = Foam::name("%08d", i);
      produces '00001234'

  Alternative using string streams:

      std::ostringstream buf;
      buf.fill('0');
      buf << setw(8) << i;
      s = buf.str();

  Note that the format specification can also be slightly more complex:

     Foam::name("output%08d.vtk", i);
     Foam::name("timing=%.2fs", time);

It remains the caller's responsibility to ensure that the format mask
is valid.
This commit is contained in:
Mark Olesen
2016-07-01 08:23:13 +02:00
parent 6d5db96ad9
commit cae7ce37f5
13 changed files with 266 additions and 32 deletions

View File

@ -3,7 +3,7 @@
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation
\\/ M anipulation |
\\/ M anipulation | Copyright (C) 2016 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
@ -31,6 +31,10 @@ Description
#include "dictionary.H"
#include "IOstreams.H"
#include "int.H"
#include "uint.H"
#include "scalar.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
@ -118,6 +122,8 @@ int main(int argc, char *argv[])
Info<< "after replace: " << test2 << endl;
}
cout<< "\nEnter some string to test:\n";
string s;
Sin.getLine(s);
@ -126,7 +132,39 @@ int main(int argc, char *argv[])
cout<< "output string with " << s2.length() << " characters\n";
cout<< "ostream<< >" << s2 << "<\n";
Info<< "Ostream<< >" << s2 << "<\n";
Info<< "hash:" << hex << string::hash()(s2) << endl;
Info<< "hash:" << hex << string::hash()(s2) << dec << endl;
cout<< "\ntest Foam::name()\n";
Info<< "hash: = " << Foam::name("0x%012X", string::hash()(s2)) << endl;
// test formatting on int
{
label val = 25;
Info<<"val: " << val << "\n";
Info<< "int " << val << " as word >"
<< Foam::name(val) << "< or "
<< Foam::name("formatted >%08d<", val) << "\n";
}
// test formatting on scalar
{
scalar val = 3.1415926535897931;
Info<< "scalar " << val << " as word >"
<< Foam::name(val) << "< or "
<< Foam::name("formatted >%.9f<", val) << "\n";
}
// test formatting on uint
{
uint64_t val = 25000000ul;
Info<<"val: " << val << "\n";
Info<< "uint64 " << val << " as word >"
<< Foam::name(val) << "< or "
<< Foam::name("formatted >%08d<", val) << "\n";
}
Info<< "\nEnd\n" << endl;
return 0;