如何在Win32控制台应用程序中解析参数?

时间:2013-08-12 14:41:43

标签: winapi arguments

大家。我知道有很多相关的线程,但我不能很好地理解它们,所以我决定写自己的。

我正在尝试编写Win32控制台应用程序,我想这样做:

假设我的名字应用程序是:MyApp.exe,所以我希望每次输入命令行时都这样:

MyApp.exe -W Hello

我的应用在输出中写入“Hello”。与其他参数相同。基本上,我想控制我想要的每一个论点,但我不知道该怎么做。

这就是我的全部:

    #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

int main(int argc, char *argv [])
{

    int count;


    printf("This program was called with  \"%s\". \n", argv[1]);
    printf("\n");

    system("Pause");

}

我的意思是,我知道每个参数都在argv数组中,但我不知道如何解析它,如:

if(argv[1] == "-W")

它不起作用。

非常感谢!

2 个答案:

答案 0 :(得分:0)

你不能使用==进行字符串比较,你需要像

这样的东西
if (strcmp(argv[1], "-W") == 0)

对于不区分大小写的比较,您需要使用_stricmp()代替。

请参阅String Manipulation上的这篇MSDN文章。

答案 1 :(得分:0)

如果您使用的是C,请使用strcmp功能:

if(strcmp(argv[1], "-W") == 0) { /* the first argument is -W */ }

如果您使用的是C ++,请使用operator==

if(std::string(argv[1]) == "-W") { /* the first argument is -W */ }
相关问题