stringTemplates.C
Go to the documentation of this file.
1/*---------------------------------------------------------------------------*\
2 ========= |
3 \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4 \\ / O peration |
5 \\ / A nd | www.openfoam.com
6 \\/ M anipulation |
7-------------------------------------------------------------------------------
8 Copyright (C) 2018 OpenCFD Ltd.
9-------------------------------------------------------------------------------
10License
11 This file is part of OpenFOAM.
12
13 OpenFOAM is free software: you can redistribute it and/or modify it
14 under the terms of the GNU General Public License as published by
15 the Free Software Foundation, either version 3 of the License, or
16 (at your option) any later version.
17
18 OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
19 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21 for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
25
26\*---------------------------------------------------------------------------*/
27
28#include <cstdio>
29
30// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
31
32// Could also consider generalizing with C++11 variadic templates
33
34template<class PrimitiveType>
35std::string::size_type Foam::string::string_printf
36(
37 std::string& output,
38 const char* fmt,
39 const PrimitiveType& val
40)
41{
42 // Use snprintf with zero to establish the size (without '\0') required
43 int n = ::snprintf(nullptr, 0, fmt, val);
44 if (n > 0)
45 {
46 output.resize(n+1);
47 char* buf = &(output[0]);
48
49 // Print directly into buffer, no stripping desired
50 n = ::snprintf(buf, n+1, fmt, val);
51 output.resize(n);
52 }
53 else
54 {
55 output.clear();
56 }
57
58 return output.size();
59}
60
61
62template<class PrimitiveType>
63std::string::size_type Foam::string::string_printf
64(
65 std::string& output,
66 const std::string& fmt,
67 const PrimitiveType& val
68)
69{
70 return string_printf(output, fmt.c_str(), val);
71}
72
73
74// ************************************************************************* //
label n
static std::string::size_type string_printf(std::string &output, const char *fmt, const PrimitiveType &val)
A printf-style formatter for a primitive.
static Ostream & output(Ostream &os, const IntRange< T > &range)
Definition: IntRanges.C:66