Reputation: 2346
I need to convert from char* to wchar. Here is how i am doing.
char * retrunValue= getData();
size_t origsize = strlen(returnValue) + 1;
const size_t newsize = 200;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, returnValue, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
getData() function returns a char* value for example "C:/Documents and Settings" when i tried to print the converted value "wcstring": the value is not correct: it is something like this "C:/Documen9" or something garbage. 1- Please tell me is it safe to convert from char* to wchar in this way, as i am doing 2- How can i get the original value as returned by getData() function
Thanks, Regards
UPDATE:
size_t origsize = strlen(returnValue) + 1;
const size_t newsize = 200;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
wsprintf(wcstring, newsize, L"%S (wchar_t *)", returnValue);
added this but it says. "argument of type "size_t is incompatible with parameter of type "LPCWSTR" "
Upvotes: 1
Views: 15367
Reputation: 36537
Don't use mbstowcs()
for such conversions unless the char*
really points to a multibyte string (not every char
string is a multibyte string!). It might break when using char
values above 127 (e.g. umlauts and other special characters).
As you'd like to concat another string anyway, just use wsprintf()
:
// Visual Studio
wsprintf(wcstring, newsize, L"%S (wchar_t *)", returnValue);
// GCC
wsprintf(wcstring, newsize, L"%ls (wchar_t *)", returnValue);
Upvotes: 3
Reputation: 91320
mbstowcs_s(&convertedChars, wcstring, newsize, returnValue, _TRUNCATE);
^^^
You're passing the wrong size.
Upvotes: 5