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

Started by
5 comments, last by henryksienkiewicz 10 years, 10 months ago

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?

Advertisement

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.

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.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

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.

Can you be more explicit on what exactly is going wrong?

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.

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.

This topic is closed to new replies.

Advertisement