0

is there any other possibility to concatenate a DebugOutputString besides this:

std::ostringstream outs;   
outs.precision(6);
outs << mMainWndCaption << _T("FPS: ") << fps;
DebugOutputString(_T(outs.str().c_str()));

Maybe something more easy to output like in printf?

I'm looking for something like DebugOutputString(_T("FPS: %i", fps)); for example

sashoalm
  • 75,001
  • 122
  • 434
  • 781
Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50

2 Answers2

1

One problem with the ostringstream approach is that you could run into interesting results if you're building a unicode application. I guess you're not using unicode here, as:

DebugOutputString(_T(outs.str().c_str()));

will not compile - it will pre-process to:

DebugOutputString(Louts.str().c_str());

Even to do it properly you would need to conditionally use either basic_ostringstream<char> or basic_ostringstream<wchar_t> based on your project settings. But I digress.


Have a look at the FormatMessage API call. There are some caveats to its use, such as whether the system allocates memory for you, and if so you need to delete the buffer, etc. And it has some slightly different formatting options. But it would do sort of what you want.

In your case, you can write a method that would take your parameters and pass them directly to DebugOutputString - in fact, the API page provides an example that returns a formatted buffer... you just need to remember to LocalFree it after use.

Here's a quick version:

void OutputFormattedDebug(LPTSTR pMsg, ...) {
    LPTSTR pBuffer = NULL;
    va_list args = NULL;
    va_start(args, pMsg);
    FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER, pMsg, 0, 0, (LPTSTR)&pBuffer, 0, &args);
    va_end(args);

    if (pBuffer) {
        OutputDebugString(pBuffer);
        LocalFree(pBuffer);
    }
}
...
OutputFormattedDebug(TEXT("Just a test: %1\n"), TEXT("Hello"));

This outputs Just a test: Hello in the debug window. It gets a little freaky if you're specifying widths and things, but a look at the documentation should sort you out.

icabod
  • 6,992
  • 25
  • 41
  • There is a problem with "va_list args = NULL;": a va_list cannot be initialized, it needs to be changed to "va_list args;" – Heng Li Jul 10 '20 at 17:26
0

Just yesterday, I put this into one of my own projects.
Maybe it will help you:

void DebugWrite(LPCTSTR format, ...)
{
    CString text;
    va_list args;
    va_start(args, format);
    text.FormatV(format, args);
    va_end(args);

    OutputDebugString((LPCTSTR)text);
}

You can call it with:

DebugWrite(_T("FPS: %i"), fps);
abelenky
  • 63,815
  • 23
  • 109
  • 159