C/C++语言中的main函数,经常带有参数argc,argv,如下: 

[cpp]  view plain copy
int main(int argc, char** argv)  

 

       这两个参数的作用是什么呢?argc 是指命令行输入参数的个数,argv存储了所有的命令行参数。假如你的程序是hello.exe,如果在命令行运行该程序,(首先应该在命令行下用 cd 命令进入到 hello.exe 文件所在目录) 运行命令为:

[cpp]  view plain copy
hello.exe Shiqi Yu  

      那么,argc的值是 3,argv[0]是"hello.exe",argv[1]是"Shiqi",argv[2]是"Yu"。

Main函数中参数argc,argv说明_c++Main函数中参数argc,argv说明_c++_02

      下面的程序演示argc和argv的使用:

[cpp]  view plain copy
#include <stdio.h>  
  
int main(int argc, char ** argv)  
{  
    int i;  
    for (i=0; i < argc; i++)  
        printf("Argument %d is %s.\n", i, argv[i]);  
  
    return 0;  
}  

      假如上述代码编译为hello.exe,那么运行:

[cpp]  view plain copy
 hello.exe a b c d e  

      将得到

[cpp]  view plain copy
Argument 0 is hello.exe.  
Argument 1 is a.  
Argument 2 is b.  
Argument 3 is c.  
Argument 4 is d.  
Argument 5 is e.  

       运行:

[cpp]  view plain copy
hello.exe lena.jpg  

      将得到

[cpp]  view plain copy
Argument 0 is hello.exe.  
Argument 1 is lena.jpg.