关于 argc 和 argv 的说明

标签 c

我对argc和argv有一些疑问,我似乎无法理解这个概念,我应该使用它们做什么以及我应该如何使用它们?

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

#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;
}

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

最佳答案

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

  • argv为接收参数数组,为字符串数组。

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

./text 145 643

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

关于关于 argc 和 argv 的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981565/

相关文章:

c - C 上的预处理器

c - 打印一个字符数组(C)只有第一个字母

c - 尝试运行 MPI 矩阵乘法示例

c - 通过 pid 监听来自进程的信号

c++ - Arduino 上的 C/C++ 字符串 .replace() 函数不起作用

c - 通过按位运算获取两个数中的较大者

c - fork 如何使用 PID 杀死一个进程

c - 如何部分预处理具有特定工作目录的 C 文件

C - 如何修复添加时间偏移,计算错误

c++ - pthread_mutex_unlock如何区分线程?