【问题标题】:How to parse arguments in a Win32 Console Application?如何解析 Win32 控制台应用程序中的参数?
【发布时间】:2013-08-12 22:54:51
【问题描述】:

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

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

假设我的名字app是: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")

它不起作用。

非常感谢!

【问题讨论】:

标签: winapi arguments


【解决方案1】:

如果您使用 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 */ }

【讨论】:

    【解决方案2】:

    您不能使用== 进行字符串比较,您需要类似的东西

    if (strcmp(argv[1], "-W") == 0)
    

    对于不区分大小写的比较,您需要改用_stricmp()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-04
      • 2013-01-06
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      相关资源
      最近更新 更多