讲解命令行参数

命令行(command line):是在命令行环境中,用户为运行程序输入命令的行。

命令行参数(command-line argument): 是同一行的附加项。

C编译器允许main()没有参数或者有两个参数

第一个参数:argc(argument count)参数计数,是一个整数

第二个参数:argv(argument value)参数值,是一个指针数组

系统用空格表示一个字符串的结束和下一个字符串的开始。

例如在命令行下输入:repeat Resistance is futile

包括命令名repeat在内有4个字符串,其中后3个供repeat使用,即参数。

这时候argc是4。argv依次存储3个参数的字符串地址。

 1 #include <stdio.h>
 2 
 3 int main(int argc,char *argv [])
 4 {
 5     int count;
 6 
 7     printf("The command line has %d arguments:\n",argc-1);
 8     for(count =1;count <argc;count++)
 9         printf("%d: %s\n",count,argv[count]);
10     printf("\n");
11 
12     return 0;
13 }

编译为可执行文件repeat,下面是通过命令行运行该程序后的输出:

C>repeat Resistance is futile

The command line has 3 arguments:

1: Resistance

2: is

3: futile

参数声明时候也会用到:char **argv;

char **argv与char *argv [] 等价;

但是char *argv []更能清晰地表示一系列字符串; 

猜你喜欢

转载自www.cnblogs.com/grooovvve/p/9938869.html