WinMain参数

时间:2013-07-26 16:50:29

标签: c++ parameters arguments argv

我的问题是参数只检索每个参数中的第一个字母,为此我不知道为什么.. 有人可以详细说明吗?

#include <Windows.h>
#include <string>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hpInstance, LPSTR nCmdLine, int iCmdShow){

LPWSTR *szArglist;
    int nArgs = 0;
    szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
    std::string a;
    for(int i=0; i<nArgs; i++){
        a += (LPCSTR)szArglist[i];
    }

    MessageBox(NULL, (LPCSTR)a.c_str(), (LPCSTR)a.c_str(), MB_OK);

    LocalFree(szArglist);
return 0;
}

我认为问题出在CommandLineToArgvW(GetCommandLineW(), &nArgs);

之内

2 个答案:

答案 0 :(得分:2)

LPWSTR的类型定义为wchar_t *szArglistwchar_t *的数组。宽字符是2个字节而不是1个字节,因此字母可能表示为:

0x0038 0x0000

但是,如果你拿这些字节并说'嘿,假装我是char *,这看起来像一个字母(0x0038)的C字符串,因为第二个字符(0x0000)为空,在C样式字符串中表示字符串的结尾。

你遇到的问题是你试图将宽字符(wchar_t)放入非宽(char)字符串中,这是一个更复杂的操作。

解决方案:要么在任何地方使用wstring / wchar_t(对应于LPWSTR / LPCWSTR),要么在任何地方使用字符串/字符(我相信对应于LPSTR和LPCSTR)。请注意,“使用unicode”的项目设置应与您的决定相符。尽量不要混合这些!

答案 1 :(得分:0)

不应该只是

int WINAPI 
WinMain(HINSTANCE hInstance, HINSTANCE hpInstance, LPSTR nCmdLine, int iCmdShow)
{
    MessageBoxA(NULL, nCmdLine, nCmdLine, MB_OK);
    return 0;
}

int WINAPI 
WinMain(HINSTANCE hInstance, HINSTANCE hpInstance, LPSTR nCmdLine, int iCmdShow)
{
    MessageBoxW(NULL, GetCommandLineW(), GetCommandLineW(), MB_OK);
    return 0;
}

相关问题