From 537032d2855de03ad143dba9538ec8d7482ce9b5 Mon Sep 17 00:00:00 2001 From: Norihiro Watanabe <norihiro.watanabe@ufz.de> Date: Fri, 10 Jun 2016 12:29:02 +0200 Subject: [PATCH] add format() in StringTools --- BaseLib/StringTools.cpp | 22 ++++++++++++++++++++-- BaseLib/StringTools.h | 3 +++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/BaseLib/StringTools.cpp b/BaseLib/StringTools.cpp index 88a0e721863..67694745465 100644 --- a/BaseLib/StringTools.cpp +++ b/BaseLib/StringTools.cpp @@ -16,10 +16,11 @@ #include <algorithm> #include <cctype> +#include <cstdarg> +#include <cstdio> #include <iomanip> -#include "logog/include/logog.hpp" - +#include <logog/include/logog.hpp> #include <boost/algorithm/string/replace.hpp> namespace BaseLib @@ -77,6 +78,23 @@ std::string const& tostring(std::string const& value) return value; } +std::string format(const char* format_str, ... ) +{ + va_list args; + va_start(args, format_str); + // get the number of chars to write + va_list args_tmp; + va_copy(args_tmp, args); + int char_length = std::vsnprintf(nullptr, 0, format_str, args_tmp); + va_end(args_tmp); + // allocate buffer and store formatted output there + std::vector<char> buffer(char_length + 1); // note +1 for null terminator + vsnprintf(buffer.data(), buffer.size(), format_str, args); + va_end(args); + + return std::string(buffer.data()); +} + } // end namespace BaseLib #ifdef MSVC diff --git a/BaseLib/StringTools.h b/BaseLib/StringTools.h index 8c379026958..7ff25e9b5f4 100644 --- a/BaseLib/StringTools.h +++ b/BaseLib/StringTools.h @@ -79,6 +79,9 @@ template<typename T> std::string tostring(T const& value) //! \overload std::string const& tostring(std::string const& value); +//! returns printf-like formatted string +std::string format(const char* format_string, ... ); + } // end namespace BaseLib #ifdef MSVC -- GitLab