关于argc和argv的澄清

问题描述 投票:0回答:2

我对什么是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;
}

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

c
2个回答
7
投票
  • argc是从命令行调用时传递给程序的参数数量。
  • argv是接收参数的数组,它是一个字符串数组。

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

./text 145 643

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


0
投票

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

gcc hello.c -o hello

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

从命令行运行该文件时,可以将命令行参数作为程序输入的一种方式。

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

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

  • argc是传递的命令行参数的数量。在上面的例子中,那就是3。
  • argv[]是一个字符串数组,在这种情况下是3个字符串。 argv[1]将等于“arg1”,argv[2]将等于“arg2”。 “./hello”将在argv[0]

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

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

© www.soinside.com 2019 - 2024. All rights reserved.