Error with const wchat_t

There is a class Link, with private variable std::wstring _name; Method name() returns c string:

1
2
3
4
inline const wchar_t * Link::name() const
{
	return _name.c_str();
}


Now I try to use this function to get name name of item in listbox:

char buffer[50];
strcpy(buffer, LinkListBox_GetSel(GetDlgItem(dialog, IDC_TR_ID))->name());

and I got error:
Error 1 error C2664: 'strcpy' : cannot convert parameter 2 from 'const wchar_t *' to 'const char *'

So this tells me that the result of the name() is wide char string. It seems non sense to me. I just want to copy the string to check what it the name of the item. Any explanation why this happen and how to correct it?

Note:
While debuging it really shows the string is type const wchar_t*
but I thought c string is just char array. That's confusing. How to convert this to copy to char array?
Last edited on
c_str() returns a const char*.
You've told your compiler that your method returns a const wchar_t*.
That's what the compiler doesn't like.
I see, so it seems the return type of this function to be mistake. That type does not make any sense to return wide characters, when the function should return c string...

On some places in program which source code I study, there are things like this:

1
2
3
4
5
6
7
8
9
LRESULT index = Combo_AddW(combobox, list->name(), list);

LRESULT Combo_AddW(HWND combobox, LPCWSTR string, const void * data)
{
	LRESULT index = Combo_AddStringW(combobox, string);
	Combo_SetItemData(combobox, index, data);

	return index;
}


So I wonder how the program can work, it expects LPCWSTR, but inside the function name() is c_str ...
Last edited on
c_str() returns a const char*.

Only if you call it on a std::string (aka std::basic_string<char>)

As the OP says, _name is of type std::wstring (aka std::basic_string<wchar_t>), so c_str() returns a const wchar_t*

The mistake is passing the return of Link::name() to strcpy when you should have used wcscpy
http://www.cplusplus.com/reference/cwchar/wcscpy/

1
2
wchar_t buffer[50]; //  now a wide char buffer
wcscpy(buffer, LinkListBox_GetSel(GetDlgItem(dialog, IDC_TR_ID))->name());


Andy
Last edited on
Oh so, thank you very much!
Topic archived. No new replies allowed.