C++ main函数中参数argc和argv

argc 是 argument count的缩写,表示传入main函数的参数个数;

argv 是 argument vector的缩写,表示传入main函数的参数序列或指针,并且第一个参数argv[0]一定是程序的名称,并且包含了程序所在的完整路径,所以确切的说需要我们输入的main函数的参数个数应该是argc-1个;

下面的程序演示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.

在cmd输入并运行

hello.exe lena.jpg

将得到

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

下一个例子演示使用opencv显示一幅图片:

#include <iostream>
#include <core/core.hpp>
#include <highgui/highgui.hpp>
using namespace std;
using namespace cv;
 
void main(int argc,char **argv)
{
	Mat image=imread(argv[1]);
	imshow("Lena",image);
	waitKey();
}

注意读入的参数是argv[1],在命令提示符窗口输入图片路径并运行: 

参考:

[C/C++基础知识] main函数的参数argc和argv

C++ main函数中参数argc和argv含义及用法

Main函数参数argc,argv说明

猜你喜欢

转载自blog.csdn.net/qq_33835307/article/details/81096838