开发者

How do I convert a WCHAR * to a regular string?

开发者 https://www.devze.com 2023-01-26 00:05 出处:网络
So in Win32 API, I have my main function defined thus: wmain(int argc, WCHAR* argv[]) I\'m passing some arguments to it, and I\'d like to e开发者_Python百科xecute a switch case based on the value of

So in Win32 API, I have my main function defined thus:

wmain(int argc, WCHAR* argv[])

I'm passing some arguments to it, and I'd like to e开发者_Python百科xecute a switch case based on the value of the argument, something like this.

wmain(int argc, WCHAR* argv[])
{
    char* temp = argv[];
    switch (temp) {
    case "one": blah blah;
...
}

Of course, the temp=argv[] doesn't work, I'm looking for a suggestion to convert it. Right now I have an if-else-if thing going on, and it's VERY inefficient!

The reason I need to convert it is because I cannot execute a switch case on a WCHAR*.

Thanks for looking.


You can't execute a switch on a char* either. (But when you actually need to convert WCHAR* to char*, use WideCharToMultiByte)

You need to use if/else if with lstrcmpi, CompareString or some other string compare function.

Alternatively, use one of the parameter parser libraries like argtable or getopt


I am not sure if this is a good idea to do. A WCHAR* could contain unicode characters which cannot be mapped to a char* in a meaningful way. In case you want to ignore this, there is a forum post at http://www.codeguru.com/forum/showthread.php?t=336106 which has some suggestions for converting from WCHAR* to char*.


Try converting it from std::wstring to std::string, its easy, maybe there is a shorter way.

Convert WCHAR* to std::wstring using std::wstring constractor, and then use one of std::wstring method to convert to std::String


Here's a quick example I wrote some time ago.

Create a new win32 console application and select ATL support. Add this and compile/run...

#include "stdafx.h"
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
// A _TCHAR is a typedef'd, depending on whether you've got a unicode or MBCS build

// ATL Conversion macros are documented here
// http://msdn.microsoft.com/en-us/library/87zae4a3(VS.80).aspx
// Declare USES_CONVERSION in your function before using the ATL conversion macros
// e.g. T2A(), A2T()    
USES_CONVERSION;

TCHAR* pwHelloWorld = _T("hello world!");
wcout << pwHelloWorld << endl;

// convert to char
char* pcHelloWorld = T2A(pwHelloWorld);
cout << pcHelloWorld << endl;


cin.get();

return 0;
}

Of course, you can't switch on a string, but this should give you the info you need in order to read a WCHAR into a char. From there, you can convert to int easily enough.. Hope this helps ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号