How do I print a floating point number in a Visual C ++ messagebox?
I have a floating point number. I would like to print it in the message box. How to do it?
MessageBox(hWnd, "Result = <float>", L"Error", MB_OK);
update:
I do this and it prints Chinese characters inside the message.
float fp = 2.3333f;
sprintf(buffer,"%f",fp);
MessageBox(hWnd, LPCWSTR(buffer), L"Error", MB_OK);
a source to share
Since you are using versions wchar_t
for Win32 functions, you should use swprintf
instead 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 possible buffer overflows, you can 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 the std::wostringstream
one declared in <sstream>
:
float fp = 2.3333f;
std::wostringstream ss;
ss << fp;
MessageBox(hWnd, ss.str().c_str(), L"Error", MB_OK);
a source to share
You are using the Unicode version of the MessageBox, so you need to include the string "Error" prefixed with an L - this indicates that it should use wide (16-bit) characters. As dalle said, this means you must specify the buffer as wchar_t and use the appropriate version of printf. Wfc_t.
You will see Chinese characters because they interpret your byte string as a wchar_t string. After all, you are explicitly using the buffer to be a wchar_t string.
a source to share