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

thi*_*ary -1 c arguments

我只是在玩弄

  int main(int argc, int *argv[void])
Run Code Online (Sandbox Code Playgroud)

函数,我试图使一个程序读取数字参数的数量.

理论上(在我自己疯狂的妄想心中),这应该工作:

#include <stdio.h>

int main(int argc, char *argv[])
{
 int count;
 printf("%d\n", sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)

但无论我在命令行中作为参数放置什么,我总是得到4(一个字4个字节?)

如何调整此代码,以便在我输入时

./program 9 8 2 7 4 3 1
Run Code Online (Sandbox Code Playgroud)

我得到:

7
Run Code Online (Sandbox Code Playgroud)

非常感激!

Rya*_*yan 6

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`argc`也会计算可执行文件本身的名称. (3认同)