(1)含义
argc为输入参数个数,argv中存储参数信息。如命名test.cpp,内容如下:
#include <stdlib.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
double width; // LINE 1
double hight; // LINE 2
width= strtol(argv[1],NULL,10); // LINE 3
hight= strtol(argv[2],NULL,10); // LINE 4
}
调用格式:test.exe 20 50
则argc=3,argv[0]为‘“test.exe”函数名;argv[1]为“20”,第一个参数;argv[2]为“50”,第二个参数。
(2)参数传递与获取
【1】输入参数
输出参数必须(1)为字符形式;(2)各参数之间要用空格隔开。
上述例子matlab调用exe的形式为:
system(['test.exe 20 50'])。
或者使用变量时为:
width = ‘20’; hight =‘50’; % 必须为字符型
system([‘test.exe’,' ',width,' ',hight]); %中间必须有空格
【2】获取参数
由于输入的参数为字符型,所以获取数值时,需要将整个字符串转为数值。若将上述例子的LINE3~LINE4修改为:
width = *argv[1]; hight = *argv[2]; 则得到width = 2;hight = 5;因为只获取了第一个字符,而不是字符串。可以利用以下两个函数进行字符串转整型:
(1)strtol函数(string to long)。如:width= strtol(argv[1],NULL,10);
(2)atoi函数(ASCII to long int)。如:width = atoi(argv[1]);
注:strtol函数比atoi函数更规范。http://blog.csdn.net/tenfyguo/article/details/5866279
http://blog.csdn.net/liubf1994/article/details/50505880