我只是在玩弄
int main(int argc, int *argv[void])
函数,我正在尝试编写一个读取数字参数数量的程序。
理论上(在我自己疯狂的妄想中),这应该有效:
#include <stdio.h>
int main(int argc, char *argv[])
{
int count;
printf("%d\n", sizeof(int));
}
但无论我在命令行中输入什么参数,我总是得到 4(一个词 4 个字节?)
如何稍微调整一下这段代码,以便当我输入时
./program 9 8 2 7 4 3 1
我得到:
7
非常感谢!
最佳答案
argc
表示传入的命令行参数的数量。您可以将其用作 main 第二个参数 argv
的索引。如果您想要所有参数不包括第一个参数(程序名称),那么您需要递减 argc,并递增 argv。
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/*
* forget about the program name.
*/
argv++;
argc--;
int i;
unsigned int totalNumbers = 0;
printf("Total number of arguments: %d\n", argc);
for(i = 0; i < argc; i++) {
printf("argv[%d]=%s\n", i, argv[i]);
errno = 0;
long num = strtol(argv[i], NULL, 10);
if(!(num == 0L && errno == EINVAL))
totalNumbers++;
}
printf("Total number of numeric arguments: %u\n",
totalNumbers);
return 0;
}
关于c - 如何用 C 语言编写一个程序来计算作为参数的数字数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131484/