首页 > 解决方案 > 使用 main() 参数向量

问题描述

我正在尝试使用 main() 参数向量来获取三个选项,它会输出所有三个结果。为什么它不能工作?

#include <ctype.h>
#include <stdio.h>
void output_1(char *str);
void output_2(char *str);
void output_3(char *str);
int main(int argc,char *argv[])
{
    char str[40];

    gets(str);
    
    if (argv[1]="-p")
    {
        output_1(str);
    }
    if (argv[1]="-u")
    {
        output_2(str);
    }
     if (argv[1]="-l")
    {
        output_3(str);
    }
}

output_1/2/3 的定义无关紧要。

标签: cmain

解决方案


C 字符串比较使用strcmp.
这是有关如何测试命令行参数并确保解析可靠的代码示例(需要检查参数的数量)。然而,解析参数最好使用getopt功能来完成。

#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{

    if (argc != 2)
    {
        printf("missing arguments");
        return -1;
    }   
    if (!strcmp(argv[1],"-p"))
    {
       printf("-p");
    }
    else
    {
         printf("unknwon arg %s",argv[1]);
    }
}

推荐阅读