Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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[i]);

		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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Can you be more explicit on what exactly is going wrong?

Share this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this