我对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/