Reputation: 63
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!
Upvotes: 1
Views: 468
Reputation: 63
@Lightness Races with Monica put me in the right direction :)
converted to wstring and works as expected
//char buffer[11]; // 32 bits, 10 characters + 1 for terminating null character
std::wstring ws1 = std::to_wstring(m_timer.GetFramesPerSecond());
std::wstring 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();
Upvotes: 0
Reputation: 385144
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
. 😊
Upvotes: 1