Thursday, September 25, 2014

printf-like function that returns std::string


std::string text = stdprintf("Function %s failed with error %i", functionName, ::GetlastError());

#include <windows.h>
#include <string>
#include <memory>

std::string stdprintf(const char* format, va_list args)
{
    std::unique_ptr output;
    int size = ((int)strlen(format)) * 2;

    for (;;)
    {
        output.reset(new char[size]);
        strcpy_s(&output[0], size, format);

        int result = vsnprintf_s(&output[0], size, _TRUNCATE, format, args);

        if ((result >= 0) && (result < size))
        {
            break;
        }

        size += abs(result - size + 1);
    }

    return std::string(output.get());
}

std::string stdprintf(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    std::string result = stdprintf(format, args);
    va_end(args);

    return result;
}

No comments:

Post a Comment