diff --git a/BaseLib/StringTools.cpp b/BaseLib/StringTools.cpp index 88a0e721863d478bc4dc5557776103c4b8625cc2..67694745465d727862e3e4932699eabb98dabe59 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 8c3790269588ed753baed78fc174023ef75d6990..7ff25e9b5f48fdb48046772c26bc19263ae88e58 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