MFC-> setwindowtext

Dear all,

I am facing a problem with the function setwindowtext from MFC.

Basically, i have a string in a ostringstream which i need to pass it on to a Cedit object. The error that i get is:

"Error 5 error C2664: 'CWnd::SetWindowTextW' : cannot convert parameter 1 from 'std::string' to 'LPCTSTR' ....."

The code that i use the following one:

1
2
3
4
5
6
7
8
CEdit * pedit;
ostringstream fos;
Cstring Svalue = "hello";
pedit = (CEdit *) GetDlgItem(CE_BOX);

fos << setw(2) << setfill('0') << hex << (int) Svalue;

pedit->SetWindowText(fos.str().c_str());


any clues here?

Thanks
Yes. Use std::wstring, as the error message does say. However, you should use CString::Format() instead of stringstream.

If you use MFC, do it the MFC way.
Right,

i have tried the following:

1
2
3
4
5
6
7
8
9
10
11
CEdit * pedit;
ostringstream fos;
std::wstring element;
std::Cstring Svalue = "hello";
pedit = (CEdit *) GetDlgItem(CE_BOX);

fos << setw(2) << setfill('0') << hex << (int) Svalue; // 

element = fos.str().c_str(); // First error HERE.

pedit->SetWindowText(element); // Second error HERE 



But i get several errors:

1. in line (First error HERE): error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const char *' (or there is no acceptable conversion)

2. in line (Second error HERE): error C2664: 'CWnd::SetWindowTextW' : cannot convert parameter 1 from 'std::wstring' to 'LPCTSTR'.

With regards to the use of cstring::format(), it seems to me that if I change now the code i will get the same error as the second line one.


You can't pass a std::wstring as argument to CEdit->SetWindowText, as you are trying to do. Use c_str() member as this:
pedit->SetWindowText(element.c_str()); // Second error HERE

As for the first error, you cannot use const char* as argument of std::wstring constructor, as you do in this line:
element = fos.str().c_str(); // First error HERE.

fos is a ostringstream type, but you need to be of type wostringstream
Right,

So here is how i solved the problem.

First of all, i need to say that my vs2010 project had an UNICODE Character set (checked in project-> properties-> general). I have now changed this to Multibyte Character set.

So considering the above, i have considered changing the program following the suggestions from modoran, that is, i use the MFC style to using CString::Format().

So in order to achieve this my code would be as follows:

1
2
3
4
5
6
7
8
9
10
11
12
CEdit * pedit;
ostringstream fos;
std::string element;
std::Cstring Svalue = "hello";
pedit = (CEdit *) GetDlgItem(CE_BOX);

fos << setw(2) << setfill('0') << hex << (int) Svalue; 
fos.Format("%02X",(int) Svalue);

element = fos; 

pedit->SetWindowText(element.c_str()); 


Thanks for the help
Topic archived. No new replies allowed.