• 14
• 12
• 9
• 10
• 9

# some help with command line parsing (got everything to work..sort of)

This topic is 1754 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I decided to try my hand at command line parsing and I found a good tutorial here: http://www.cplusplus.com/articles/DEN36Up4/

But I tried to do this:

#include <iostream>
#include <string>
#include <map>
#include <fstream>
using namespace std;

typedef map<string,string> Arguments;
int main(int argc, char** argv)
{
Arguments args;
if(argc < 3)
{
cout << "ERROR: " << endl;
return 1;
}
for(int i = 1; i < argc; i++)
{
string name = string(argv);

if(name == "--Help")
{
if(i + 1 < argc)
{
char* file = argv[i++];
ofstream outfile;
outfile.open(file);
if(outfile.is_open())
{
outfile << "Hello Jesus." << endl;

}
outfile.close();
cout << "File Created: " << endl;
}

}
}
return 0;
}


as you can see, i'm trying to create a file when "--Help" is used (this is just a test, the final command wont be --Help. any ideas?

##### Share on other sites

You have:

char* file = argv[i++];


If the filename is to be supplied after "--Help" perhaps you want '++i'.

Just as a side note, the strings == is case-sensitive so '--help' wouldn't match.

##### Share on other sites

You might want to clarify that error you are outputing as well as just ERROR tells a user nothing of what he did.

Also you might want to be really careful in incrementing or decrementing your loop counter outside the loop definition as it makes errors hard to spot and could potentially allow you to index out of bounds.

##### Share on other sites

none of that worked...........well, there has to be a way to get that to work, creating a file via command line arguments....everyone else seems to know what they are doing.

##### Share on other sites
Can you be more explicit on what exactly is going wrong?

##### Share on other sites

Give us an example of the command line you are trying to pass, and what is (or isn't) happening.

Have you tried using a debugger? Or even just printing some extra statements, e.g. "Found --Hello as argument {i}", "Skipping unrecognised argument {i} {argument}" and "Created file: {filename}", along with maybe printing "Failed to open {filename}" if the file failed to open.

##### Share on other sites
Hi,
on a side note from the original problem, have you tried using boost program options?

http://www.boost.org/doc/libs/1_53_0/doc/html/program_options/tutorial.html

I haven't used it myself but it looks like it has everything what can be interesting in terms of passing command line arguments.