Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1427942
  • 博文数量: 842
  • 博客积分: 12411
  • 博客等级: 上将
  • 技术积分: 5772
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-14 14:43
文章分类

全部博文(842)

文章存档

2013年(157)

2012年(685)

分类: C/C++

2012-05-12 21:49:13




 刚开始还不知道main函数带个参数有什么用,后来发现很多可执行文件都是main函数带参的,那些带有选项的命令行命令就是这样的程序。比如ping -h,-h就是个参数。

下面是对main函数带参数的理解:

  main函数带的参数是有规定的,必须是两个参数,第一个是字符串个数(包括可执行文件名也算一个字符串),第二个是指向字符串数组的指针。
    执行的时候格式:可执行文件名 字符串1 字符串2 字符串3 ...(以空格分开)
    注意,执行的时候不能输入第一个参数(字符串个数),这个参数是系统根据你后面输入的字符串个数自动计算出来的,值是你输入的字符串个数再加1,因为可执行文件名也算一个字符串,另外,字符串数组中的第0个元素也是这个可执行文件名。



写一个简单的测试程序如下:

/***********************************************************
A test main programme with parameter 
ruanbanmao 2011-12-16
************************************************************/
# include
void info()
{
printf("Information:\n");
printf("Main function with parameter\n");
printf("Auther: ruanbanmao\n");
printf("date: 2011-12-16\n");
}

void help()
{
printf("Options:\n");
printf("-h: Help information\n");
printf("-i: The information for the programme\n");
printf("-w: Say hello world\n");
}

int main(int argc, char *argv[])
{
    if (argc > 2)
printf("Too many parameter!\n");
else if(argc < 2)
{
printf("Pls input an option\n");
help();
}
else
{
if (*argv[1] != '-')
{
printf("Error parameter\n");
help();
}
else 
{
switch(*(argv[1]+1))
{
case 'h':
help();
break;
case 'i':
info();
break;
case 'w':
printf("w: say hello world\n");
break;
default:
printf("Fault options\n");
help();
break;
}
}
}
return 0;
}
阅读(381) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~