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

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

问题描述

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



int main ,char * argv [])



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



int main()



这是什么意思,对我的程序至关重要?

解决方案

argv main()是如何将命令行参数传递给 argc

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



这些变量命名为 argc 参数计数)和 argv 约定,但它们可以被赋予任何有效的标识符: int main(int num_args,char ** arg_strings)同样有效。



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



尝试以下程序:

  #include< iostream> 

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

使用 ./ test a1 b2 c3 将输出

 有4个参数:
./test
a1
b2
c3


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[])

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?

解决方案

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

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.

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.

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

Try the following program:

#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;
    }
}

Running it with ./test a1 b2 c3 will output

Have 4 arguments:
./test
a1
b2
c3

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

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