Search code examples
cmessageboxprintf

displaying double in messagebox


I'm having issues with converting a double to a string, and then to a message box. From what i've read, sprintf is (loosely, but not the best choice due to certain points) the function i want from . Here's my example code, but i'm not sure where i'm going wrong.

DOUBLE time;
char timearray[30];
time = (double)(end.QuadPart - st.QuadPart)/(double)freq.QuadPart;
sprintf(timearray, "%lf", time);

where'd i go from here? i've tried things like;

MessageBox(NULL, timearray, TEXT("mb"), MB_OK);

But this gives the following error on the timearray parameter: error of type "*char" is incompatible with parameter of type "LPCWSTR".

Any ideas as to where i'm going wrong?


Solution

  • Probably your project is set to use wide (Unicode) characters by default, so you should use wchar_t and wsprintf (better, wnsprintf).

    double time;
    wchar_t buffer[30];
    time = (double)(end.QuadPart - st.QuadPart)/(double)freq.QuadPart;
    _snwprintf(buffer, sizeof(buffer)/sizeof(*buffer), L"%lf", time);
    MessageBoxW(NULL, buffer, L"mb", MB_OK);
    

    or, if you want to use the TCHARs:

    double time;
    TCHAR buffer[30];
    time = (double)(end.QuadPart - st.QuadPart)/(double)freq.QuadPart;
    _sntprintf(buffer, sizeof(buffer)/sizeof(*buffer), _T("%lf"), time);
    MessageBox(NULL, buffer, _T("mb"), MB_OK);