Main函数参数argc,argv说明

原文地址:http://wiki.opencv.org.cn/index.php/Main%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0argc%EF%BC%8Cargv%E8%AF%B4%E6%98%8E

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

int main(int argc, char** argv)
int main(int argc, char* argv[])

这两个参数的作用: argc (argument count:即参数个数)是指命令行输入参数的个数(以空白符分隔) argv(argument value:即参数的值)存储了所有的命令行参数 假如你的程序是hello.exe,如果在命令行运行该程序,(首先应该在命令行下用 cd 命令进入到 hello.exe 文件所在目录) 运行命令为:

hello.exe Shiqi Yu

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

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

#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,那么运行

hello.exe a b c d e

将得到

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.

运行

hello.exe lena.jpg

将得到

Argument 0 is hello.exe.
Argument 1 is lena.jpg.

下面根据写一个简单的命令行的实现两个数相加的程序

[cpp]  view plain  copy
 print ?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4.   
  5. //用命令实现两个数相加  
  6. int main(int argc,char **argv)  
  7. {  
  8.     //排除没有第二个,第三个以及查看帮助的情况  
  9.     if(argv[1]==NULL || argv[2]==NULL || strcmp(argv[1],"/?")==0)  
  10.     {  
  11.         printf("Usage are as follows\n");  
  12.         return 0;  
  13.     }  
  14.     printf("%d+%d=%d\n",atoi(argv[1]),atoi(argv[2]),atoi(argv[1])+atoi(argv[2]));  
  15.     return 0;  
  16. }  

编译连接产生add.exe,然后就可以执行这样的命令,比如add 1234 5678


0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值