Roger Breton
Roger Breton

Reputation: 91

SetWindowTextW() helper function in c++

I wonder whether there is a "better way" to supply SetWindowText "text" argument than this code:

wchar_t buffer[20];
Measures10nm.CIE_L = 100.3456f;
Measures10nm.CIE_a = -9.34f;
Measures10nm.CIE_b = -56.56f;
swprintf_s(buffer, 20, L"%.2f", Measures10nm.CIE_L);    
SetWindowTextW(hEditCIE_L, buffer);
swprintf_s(buffer, 20, L"%.2f", Measures10nm.CIE_a);
SetWindowTextW(hEditCIE_a, buffer);
swprintf_s(buffer, 20, L"%.2f", Measures10nm.CIE_b);
SetWindowTextW(hEditCIE_b, buffer);

I tried to experiment with a function that I could supply a float to and who would return a wchar_t, since that's the type of argument SetTextWindow() requires but I have not been "successful" at it. I'm not even sure this is possible, technically, after all the time I experimented with various coding? Ideally, what I'd like to use is a function like this :

SetTextWindow(hEdit, floatToWchar_t(Measures10nm.CIE_L));

But I have not been able to code such a function? I experimented with something along these lines :

wchar_t floatToWchar_t(float x)
{
wchar_t buffer[20];
swprintf_s(buffer, 20, L"%f", x);
return buffer;
}

But that does not work because wchar_t is an array, I suppose. I thought about using a pointer to the array but I can't conceptualize clearly how to do it.

Any help is appreciated. Please excuse the newbie question...

Upvotes: 0

Views: 299

Answers (2)

Joseph Willcoxson
Joseph Willcoxson

Reputation: 6040

Modify for wstring ....

std::wstring floatToWideString(float x)
{
   wchar_t buffer[20];
   swprintf_s(buffer, 20, L"%f", x);
   return buffer;
}

Then

void SetWindowText(HWND hwnd, const std::wstring& s)
{
   SetWindowText(hwnd, s.c_str());
}


SetWindowText(hwnd, floatToWideString(3.1415f));

... but with all your calls to SetWindowText to the same hwnd, you're going to overwrite what's there....it's not like it is a line buffer.

Update: Also, if you get so inclined to use use MFC, or just to use <atlstr.h>, there is a CString class that has a (LPCTSTR) cast operator.

Something like:

CStringW floatToWideCString(float x)
    {
       CStringW s;
       s.Format(_T("%f"), x);
       return s;
    }

SetWindowText(hwnd, floatToWideCString(3.14));

Upvotes: 0

rveerd
rveerd

Reputation: 4006

We're talking C++ here so forget about character arrays and use std::wstring and C++ streams.

#include <sstream>

std::wstringstream ss; // String-based stream.
float f = 3.14; // Our float.
ss << f; // Output the float to the stream.
SetWindowTextW(hWnd, ss.str().c_str()); // Covert to a `wchar_t` zero-terminated string.

You can easily wrap this in a function.

void SetWindowFloat(HWND hWnd, float f);

If you need to modify how the float is converted to a string, take a look at iomanip.

Upvotes: 2

Related Questions