Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

visual c++ - Convert char[] to LPCWSTR

Can anyone help me to correct this code:

    char szBuff[64];
    sprintf(szBuff, "%p", m_hWnd);
    MessageBox(NULL, szBuff, L"Test print handler", MB_OK);

The error is, it cant convert the 2nd parameter to LPCWSTR.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For this specific case, the fix is quite simple:

wchar_t szBuff[64];
swprintf(szBuff, L"%p", m_hWnd);
MessageBox(NULL, szBuff, L"Test print handler", MB_OK);

That is, use Unicode strings throughout. In general, when programming on Windows, using wchar_t and UTF-16 is probably the simplest. It depends on how much interaction with other systems you have to do, of course.

For the general case, if you've got an ASCII (or char *) string, use either WideCharToMultiByte for the general case, or mbstowcs as @Matthew points out for simpler cases (mbstowcs works if the string is in the current C locale).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...