Search code examples
c++directxwchar-tuint32-t

Access violation when converting from uint32_t to wchar_t and storing in wstring


This might be a simple question, but I have a value in DirectXTDK that is in uint32_t. I would like to display this by concatenating it with a wchar_t.

This is what I have so far -

char buffer[1];
wchar_t* ws1 = (wchar_t *)itoa(m_timer.GetFramesPerSecond(), buffer, 10), * ws2 = L" FPS";
std::wstring s(ws1);
s += std::wstring(ws2);
const wchar_t* fps = s.c_str();

// Draw Text to the screen
m_sprites->Begin();
    m_font->DrawString(m_sprites.get(), L"DirectX Museum Scene", XMFLOAT2(10, 10), Colors::Yellow);
    m_font->DrawString(m_sprites.get(), fps, XMFLOAT2(8, 30), Colors::Yellow);
m_sprites->End();

The issue occurs when displaying FPS as garbage characters are trying to be displayed that the default font cannot handle. Without itoa, the execution will throw an exception at std::wstring s(ws1).

How can I effectively convert uint32_t to wchar_t * to display FPS properly? Thanks!


Solution

  • itoa produces an ASCII character string, not a wide string.

    That you had to throw in a C-style cast to force a pointer type change is the red flag there; you should never have to do that and, when you do, the result is normally wrong. The type system is there to help you!

    I'm also concerned by your choice of buffer size; do you know that there will only be one digit in the frames-per-second value? And where is the space for the null terminator?

    I think you wanted _itow. But, to fix the buffer problem, _itow_s would be better.

    Better still, skip the legacy stuff entirely and get yourself a nice std::to_wstring. 😊