main函数参数argc和argv应用

本文探讨了如何在C/C++程序中利用main函数的参数argc和argv。通过两个实例,展示了如何在命令行中输入参数,进行文件操作。实例1详细解释了如何在cmd中执行命令,如`test c: est.txt d: esult.txt`。实例2则介绍了如何结合OpenCV库,使用argv读取图像,用户可以方便地通过鼠标拖动图像至cmd,自动获取图像的绝对路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,自动生成绝对路径)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值