Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Command Line Parameters

I have a problem with command line parameters. I finished the program so I can start it like this from command line:

program.exe test.txt copy_test.txt

Basically, my program does the following :

  • inputs some text file
  • sorts it and copy to a new text file

BUT (always that but?!), I should start the program from command line like this:

program.exe -input=test.txt -output=copy_test.txt

And I don't know how to do that. I researched, but I didn't find any help :(

Please respond.

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

int main ( int argc, char* argv[])
{
 ifstream in(argv[1]);
 ofstream out(argv[2]);
 vector <string> sV;
 string line;
 while (in >> line)
  sV.push_back(line);
 for ( int i = 0; i < sV.size(); i++)
 sort ( sV.begin(), sV.end () );
 for ( int i = 0; i < sV.size(); i++)
 out << sV[i] << endl;
 cin.get();
 return 0;
}
like image 710
CRT_flow Avatar asked Mar 03 '26 12:03

CRT_flow


1 Answers

You should parse main's argv arguments in order to check whether they start by -input, -output etc etc.

Doing this from scratch is a hell, but luckily there are many useful libraries to do this, like boost.program_options

like image 105
peoro Avatar answered Mar 06 '26 00:03

peoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!