晨旭的博客
你想干什么!
晨旭的博客~
int main(int argc, char *argv[])的用法

解释源自此处:http://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean

原问题:

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?

翻译:

在许多c++IDE和编译器里,main函数经常会像这样:

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

但是我写的时候只会这样:

int main()

米有任何包含。这样做的目的是什么?

解释:

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 main(int argc, char *argv[])是命令行里用的

argc表示后面接的参数个数

比如:

#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

输出:

./test
a1
b2
c3

另外,int main(int argc, char *argv[])与int main(int argc, char **argv)等价。

赞赏
如非特殊说明,本站所有文章均采用知识共享 署名-非商业性使用-相同方式共享4.0国际许可协议(CC BY-NC-SA 4.0)进行许可。

发表评论

textsms
account_circle
email

  • https://secure.gravatar.com/avatar/5d19c17f6c19591fdd7cc41b148c90b9?s=80&d=mm&r=x
    Google Chrome 48.0.2564.97 Google Chrome 48.0.2564.97 Windows 8.1 x64 Edition Windows 8.1 x64 Edition
    Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36

    写掉了一个参数 标准写法应该是这样int main(int argc, char* argv[], char* envp[])

    3年前回复
    • https://secure.gravatar.com/avatar/b431bf781498d1fe47f732913dce394c?s=80&d=mm&r=x
      晨旭博主
      Google Chrome 49.0.2623.108 Google Chrome 49.0.2623.108 Windows 7 x64 Edition Windows 7 x64 Edition
      Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.108 Safari/537.36

      环境变量啊。。。。感觉用到的地方好少,,

      3年前回复

晨旭的博客~

int main(int argc, char *argv[])的用法
解释源自此处:http://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean原问题:In many C++ IDE's and compilers, when it generates the main function for…
扫描二维码继续阅读
2016-03-24