CRT_flow CRT_flow - 2 months ago 7
C++ Question

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;
}

Answer

Well, with your new format arguments, you can't just pass them as-is to the stream constructors.

You will have to check if they start with a specific string, such as with strncmp and then pass the address of the relevant bit such as argv[1]+8 for the input type.

Since you're providing --input= type prefixes, you may also want to handle the possibility that they may be in the other order as well.

For example, you can replace:

int main (int argc, char* argv[]) {
    ifstream in(argv[1]);
    ofstream out(argv[2]);

with something like:

int main (int argc, char* argv[]) {
    char *infile = 0;
    char *outfile = 0;
    for (int i = 1; i < argc; i++) {
        if (strncmp (argv[i], "--input=", 8) == 0) {
            infile = argv[i] + 8;
        } else {
            if (strncmp (argv[i], "--output=", 9) == 0) {
                outfile = argv[i] + 9;
            } else {
                std::cerr << "Invalid argument [" << argv[i] << "]" << std::endl;
                return -1;
            }
        }
    }
    if ((infile == 0) || (outfile == 0)) {
        std::cerr << "Need to specify input and output file" << std::endl;
        return -1;
    }

    ifstream in(infile);
    ofstream out(outfile);