您的位置:首页 > 大数据 > 人工智能

Main函数中参数argc,argv说明

2015-06-03 11:46 561 查看
转载自:/article/1422835.html

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

[cpp] view
plaincopy

int main(int argc, char** argv)

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

[cpp] view
plaincopy

hello.exe Shiqi Yu

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



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

[cpp] view
plaincopy

#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
plaincopy

hello.exe a b c d e

将得到

[cpp] view
plaincopy

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
plaincopy

hello.exe lena.jpg

将得到

[cpp] view
plaincopy

Argument 0 is hello.exe.

Argument 1 is lena.jpg.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: