Reputation: 6817
I have, a float number. I would like to print it inside a messagebox. How to do it?
MessageBox(hWnd, "Result = <float>", L"Error", MB_OK);
update:
I do this and it prints out chinese characters inside the messagebox.
float fp = 2.3333f;
sprintf(buffer,"%f",fp);
MessageBox(hWnd, LPCWSTR(buffer), L"Error", MB_OK);
Upvotes: 2
Views: 7999
Reputation: 18517
As you are using the wchar_t
versions of the Win32-functions you should use swprintf
instead of sprintf
:
float fp = 2.3333f;
const size_t len = 256;
wchar_t buffer[len] = {};
swprintf(buffer, L"%f", fp);
MessageBox(hWnd, buffer, L"Error", MB_OK);
To avoid potential buffer overruns you could also use _snwprintf
:
float fp = 2.3333f;
const size_t len = 256;
wchar_t buffer[len] = {};
_snwprintf(buffer, len - 1, L"%f", fp);
MessageBox(hWnd, buffer, L"Error", MB_OK);
Or better yet, use std::wostringstream
declared in <sstream>
:
float fp = 2.3333f;
std::wostringstream ss;
ss << fp;
MessageBox(hWnd, ss.str().c_str(), L"Error", MB_OK);
Upvotes: 5
Reputation: 1330
You're using the Unicode version of MessageBox, which is why you have to specify the "Error" string with the L prefix -- this tells it that it should use wide (16-bit) chars. As dalle said, this means you must specify the buffer as wchar_t, and use the corresponding wchar_t version of printf.
You'll be seeing Chinese characters because it's interpreting your string of bytes as a string of wchar_t. You are explicitly casting buffer to be a wchar_t string, after all.
Upvotes: 3
Reputation: 318548
You have to printf the message to a buffer with the %f format code and then use that in your MessageBox()
Upvotes: 1