simple sprintf wrapper

version 0

#include <memory>
#include <string>
#include <stdexcept>

template<typename ... Args>
std::string string_format( const std::string& format, Args ... args )
{
    int size_s = std::snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
    if( size_s <= 0 ){ throw std::runtime_error( "Error during formatting." ); }
    auto size = static_cast<size_t>( size_s );
    std::unique_ptr<char[]> buf( new char[ size ] );
    std::snprintf( buf.get(), size, format.c_str(), args ... );
    return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}

int main()
{
    stringg aa = format("test %d %s", 100, "abc");
    printf(aa.c_str());
    return 0;
}

version 1

#include <stdio.h>
#include <stdarg.h>

void Error (char * format, ...)
{
  char buffer[256];
  va_list args;
  va_start (args, format);
  vsnprintf (buffer, 255, format, args);


  //do something with the error

  va_end (args);
}

ref

cplusplus.com/reference/cstdio/vsnprintf/: https://cplusplus.com/reference/cstdio/vsnprintf/
cplusplus.com/reference/cstdio/snprintf/: https://cplusplus.com/reference/cstdio/snprintf/
c++ - std::string formatting like sprintf - Stack Overflow: https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf
c++ - How to pass variable number of arguments to printf/sprintf - Stack Overflow: https://stackoverflow.com/questions/1056411/how-to-pass-variable-number-of-arguments-to-printf-sprintf
Variadic functions - cppreference.com: https://en.cppreference.com/w/c/variadic

posted on 2024-08-18 22:27  yusisc  阅读(2)  评论(0编辑  收藏  举报

导航