문제

I've tried a lot of solutions, but none of them is working.

  • printf("Test : %d", 123);
  • std::cout << "Test" << 123 << std::endl;
  • ...

Actually I've setup my project's debugger like this, I'm able to write in the console using OutputDebugStringA("Test"); but this function doesn't accept more than one parameter.

How can I print something like this : ("Test : %d", 123)?

도움이 되었습니까?

해결책 3

I've finally found this solution (here and here) :

Debug.cpp:

#pragma once

#include "pch.h"
#define BUFFER_LENGTH 1024

//char* to wchar_t*
const wchar_t *GetWC(const char *c)
{
    const size_t cSize = strlen(c) + 1;
    wchar_t* wc = new wchar_t[cSize];
    mbstowcs(wc, c, cSize);

    return wc;
}

void Debug::Log(const char *format, ...)
{
    char buffer[BUFFER_LENGTH];
    va_list args;
    va_start(args, format);
    vsnprintf(buffer, BUFFER_LENGTH, format, args);
    va_end(args);
    buffer[BUFFER_LENGTH - 1] = '\0'; //prevent buffer overflow
    OutputDebugString(GetWC(buffer));
}

Debug.h:

class Debug{
public:
    static void Log(const char *format, ...);
};

We can use it like printf function:

Debug::Log("Test : %d", 123);

다른 팁

Bogy's answer is on the right track but I don't like the allocation in GetWC which looks like a memory leak, and it uses unsafe functions, try this:

void Debug::Log(const wchar_t *format, ...)
{
    wchar_t buffer[BUFFER_LENGTH];
    va_list args;
    va_start(args, format);
    _vsnwprintf_s(buffer, BUFFER_LENGTH, _TRUNCATE, format, args);
    va_end(args);
    buffer[BUFFER_LENGTH - 1] = '\0'; //prevent buffer overflow
    OutputDebugString(buffer);
}

Usage like:

Debug::Log(L"Hello %S\n", "sailor");

I found this code in a C++ training on Pluralsight that I am using for Windows 8 (you just say TRACE("Test : %d", 123); to use it):

#pragma once
#include <assert.h>

#define ASSERT assert

#ifdef _DEBUG
inline auto Trace(wchar_t const * format, ...) -> void
{
    va_list args;
    va_start(args, format);

    wchar_t buffer[256];

    ASSERT(-1 != _vsnwprintf_s(buffer, _countof(buffer) - 1, format, args));
    va_end(args);

    OutputDebugString(buffer);
}
#endif

struct Tracer
{
    char const * m_filename;
    unsigned m_line;

    Tracer(char const * filename, unsigned const line) :
        m_filename{ filename },
        m_line{ line }
    {

    }

    template <typename... Args>
    auto operator()(wchar_t const * format, Args... args) const -> void
    {
        wchar_t buffer[256];

        auto count = swprintf_s(buffer, L"%S(%d): ", m_filename, m_line);

        ASSERT(-1 != count);

        ASSERT(-1 != _snwprintf_s(buffer + count, _countof(buffer) - count, _countof(buffer) - count - 1, format, args...));

        OutputDebugString(buffer);
    }
};

#ifdef _DEBUG
#define TRACE Tracer(__FILE__, __LINE__)
#else
#define TRACE __noop
#endif
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top