c - 如何用 C 语言编写一个程序来计算作为参数的数字数量?

标签 c arguments

我只是在玩弄

  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/

相关文章:

c++ - 如何在 AES_set_encrypt_key 中使用 openssl 中的自定义 key

c - 在 C 中对多维数组列进行排序

c - 如何编写用户空间 linux block 设备驱动程序?

javascript - 使用 setTimeout 时将值传递给 javascript 中的函数

python - 将参数分配给具有相同名称的全局变量

javascript - 通过 Web API 或 libspotify 获取 Spotify 播放历史

c - 在已编译的 Linux 内核上启用 kdump

javascript - 使中间参数可选的惯用方法

Linux/庆典 : How to unquote?

python - 在 python 中用函数参数命名的列表