简体   繁体   中英

conversion from char* to wchar_t

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" "

mbstowcs_s(&convertedChars, wcstring, newsize, returnValue, _TRUNCATE);
                                      ^^^

You're passing the wrong size.

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 (eg 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM