关于argc和argv的澄清

时间:2017-02-01 13:56:04

标签: c

我对什么是argc和argv有些怀疑,我似乎无法掌握这个概念,我应该使用它们以及我应该如何使用它们?

就像我有这个程序从命令行接收-100000和100000之间的两个整数计算添加并打印结果,同时执行所有需要检查te数量的参数及其正确性。

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

int main(int argc, char *argv[])
{
    int a, b;
    char ch;

    if (argc != 4)
    {
        printf("ERROR - Wrong number of command line parameters.\n");
        exit(1);

    }

    if (sscanf(argv[1], "%d", &a) != 1)
    {
        printf("ERROR - the first parameter (%s) is not a valid integer.\n",
                argv[1]);
        exit(2);
    }

    if (sscanf(argv[2], "%d", &b) != 1)
    {
        printf("ERROR - the second parameter (%s) is not a valid integer.\n",
                argv[2]);
        exit(2);
    }
    ch = argv[3][0];

    if (ch == 'a')
        printf("The sum result is %d\n", a + b);
    else if (ch == 'b')
        printf("The subtraction result is %d\n", a - b);
    else if (ch == 'c')
        printf("The multiplication result is %d\n", a * b);
    else if (ch == 'd')
    {
        if (b != 0)
            printf("The division result is %d\n", a / b);
        else
            printf("ERROR the second value shoulb be different than 0 \n");
    }
    else
        printf("ERROR parameter (%c) does not correspond to a valid value.\n",
                ch);
    return 0;
}

但程序如何从命令行接收两个参数?我在哪里输入?我正在使用代码块。

2 个答案:

答案 0 :(得分:7)

  • argc是从命令行调用时传递给程序的参数数量。

  • argv是接收参数的数组,它是一个字符串数组。

请注意,程序名称始终自动传递。 假设您的程序可执行文件是test,当您从终端调用时:

./text 145 643

argc将为3:程序名称和两个数字
argv将是char*数组{"./text","145","643"}

答案 1 :(得分:0)

当您编写代码时,请说hello.c,您可以从终端运行它,从终端转到该目录/文件夹,然后使用像gcc这样的编译器进行编译。

gcc hello.c -o hello

如果您使用Windows,使用Turbo C或Visual Studio等编译器,则会创建.exe文件。这会创建一个可执行文件。

从命令行运行文件时,可以提供命令行参数作为程序输入的方式。

在终端上,您可以./hello arg1 arg2,其中arg1arg2是命令行参数。要了解如何使用Turbo C之类的编译器在Windows中执行此操作,see this link too

那么argcargv[]是什么? 您的main函数使用main(int argc, char *argv[])来获取命令行参数。

  • argc是传递的命令行参数的数量。在上面的例子中,那就是3。
  • argv[]是一个字符串数组,在本例中是3个字符串。 argv[1]将等于&#34; arg1&#34;并且argv[2]将等于&#34; arg2&#34;。 &#34; ./你好&#34;将在argv[0]

因此,您可以在命令行中提供命令行参数,无论是Linux还是Windows。以上解释更适用于Linux。有关Turbo C中的命令行参数(我不建议使用Turbo C),请参阅thisthis,如果是Visual C,请参阅this

要了解有关命令行参数的更多信息,请阅读this

相关问题