argc和argv参数需要从cmd中输入
实例1:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
if (argc != 3)//输入参数必须为三个,第一个为生成程序名,第二个为输入文件的路径,第三个为输出文件的路径
{
cout << "argument error!" << endl;
cout << "example: test c:/test.txt d:/testOut.txt" << endl;
system("pause");
exit(-1);
}
for (int i = 0; i<3; i++)
{
cout << argv[i] << endl;
}
ifstream fileIn;
fileIn.open(argv[1], ios::in);//根据用户设定的参数,打开输入文件
if (fileIn.fail())//如果文件打开失败,直接退出
{
cout << "fileIn open error: " << endl;
system("pause");
exit(-1);
}
ofstream fileOut;
fileOut.open(argv[2], ios::out);//根据用户设定的参数,打开(创建)输出文件
if (!fileOut)
{
cout << "fileOut open error..." << endl;
system("pause");
exit(-1);
}
char str[500];
while (!fileIn.eof())
{
memset(str, '\0', 500 * sizeof(char));
fileIn.getline(str, 500);
fileOut << str << endl;
cout << str << endl;
}
fileIn.close();
fileOut << "I have learn the usage of argc and argv in main function! Thanks to VitoLee!" << endl;
fileOut.close();
system("pause");
return 0;
}
cmd输入:
cd d:\a\test\debug
d:
test c:\test.txt d:\result.txt
实例2:结合opencv使用argv读取图像
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "argument error..." << endl;
system("pause");
exit(-1);
}
Mat img = imread(argv[1]);
imshow("1", img);
waitKey(0);
return 0;
}
cmd输入:
cd d:\a\test\debug
d:
test “图像路径”(可以用鼠标拖动图像到cmd,自动生成绝对路径)