带参数的主函数
一般情况下(许多教科书中都没有说明),我们在写程序的时候,往往忽略了主函数的参数,例如: int main() { … return 0; } 在命令行下,输入程序的名称就可以运行程序了。实际上,我们还可以通过输入程序名和相关的参数来为程序的运行提供更多的消息。参数紧跟在程序名后面,参数之间用空格分开。 这些参数被称为:command-line arguments(命令行参数),也往往被称为程序的argument list(参数表)。例如,在Linux终端,用户可以输入ls –l显示目录下文件的详细信息。这个命令中,ls是程序名称,用户调用该程序,它有一个输入参数-l。 main函数通过两个参数获取输入参数表信息,分别是argc和argv。第一个参数是一个整型的变量,它记录了用户输入的参数的个数。第二个参数argv是一个char型的指针数组,它的成员记录了指向各参数的指针。argv[0]是程序名,argv[1]是第一个参数。 例如:(TC3.0编译环境,Windows XP) #include <stdio.h> int main(int argv, char *argc[]) { printf('/nthe name of the program is %s /n', argc[0]); printf(' the program has %d argument! /n', argv - 1); if(argv > 1) { int i; printf('the arguments are:/n'); for(i=1; i<argv; i++) { printf('%s/t',argc[i]); } } return 0; } 当用户在命令行下输入:mytest 输出: the name of the program D:/WINYES/TCPP30E/OUTPUT/MYTEST.EXT the program has 0 argument! 当用户在命令行下输入:mytest aa bb cc dd e 输出: the name of the program D:/WINYES/TCPP30E/OUTPUT/MYTEST.EXT the program has 5 argument! The arguments are: aa bb cc dd e |
|