int argc, char *argv[] 是什么意思? [英] What does int argc, char *argv[] mean?

查看:33
本文介绍了int argc, char *argv[] 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多 C++ IDE 和编译器中,当它为您生成 main 函数时,它看起来像这样:

In many C++ IDE's and compilers, when it generates the main function for you, it looks like this:

int main(int argc, char *argv[])

当我在没有 IDE 的情况下编写 C++ 时,只使用命令行编译器,我输入:

When I code C++ without an IDE, just with a command line compiler, I type:

int main()

不带任何参数.这是什么意思,它对我的​​程序至关重要吗?

without any parameters. What does this mean, and is it vital to my program?

推荐答案

argvargc 是命令行参数传递给 main() 的方式代码>在 C 和 C++ 中.

argv and argc are how command line arguments are passed to main() in C and C++.

argc 将是 argv 指向的字符串数.这将(实际上)是 1 加上参数的数量,因为几乎所有的实现都会将程序的名称添加到数组中.

argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

按照惯例,变量被命名为argc(参数计数)和argv(参数向量),但是它们可以被赋予任何有效的标识符:int main(int num_args, char** arg_strings) 同样有效.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

如果您不打算处理命令行参数,它们也可以完全省略,产生 int main().

They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments.

试试下面的程序:

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}

使用 ./test a1 b2 c3 运行它会输出

Have 4 arguments:
./test
a1
b2
c3

这篇关于int argc, char *argv[] 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆