command line arguments

I have probably searched through many dozens of articles trying to figure out how to correct this. I know how to turn command line arguments in to float's and integers but all I want to do is evaluate them as a string.
I'm trying to make flags work for a command line program I'm writing and I can't believe I'm having this much trouble.

I wanted to set it up where the third argument would be reserved for flags.

[FILENAME] [INPUT] [OUTPUT] [FLAGS]

1
2
3
4
5
6
7
8
9
10
11
for (int i=3; i < argc;i++)
                {
                    switch (argv[i])
                        case '--verbose':
                            verbose=true;
                            break;
                        case '--help':
                            cout  << usage <<help;
                            return 0;
                            break; 
                }


If statements compile but it doesn't seem to evaluate them correctly. This statement won't compile because it says the switch quantity is not an integer.

How should I be doing this?
String literals are enclosed in quotation marks, not single quotes. Even so, you can't use switch for this.
This is how it's done:
1
2
3
4
5
6
7
vector<string> args(argv,argv+argc);
for (int i=3;i<argc;i++)
{
  string& arg=args[i];
  if (arg=="--verbose")verbose=true;
  else if (arg=="--help")...
}
Last edited on
Have you got your exact errors?

Two ways you can do this.

1) Use strcmp to compare your character array. It's a bit old fashioned, though.

2) Assign the argument to a string, the compare it using ==.

I would use an if statement, not a switch.

Brief example showing argument comparison
1
2
3
4
5
6
7
8
9
10
int main(int argc, char* argv[])
{
   bool verbose;
   string tmp = argv[1];

   if(tmp == "verbose")
   {
      verbose = true;
   }
}


Edit: Pipped to the post by a mile by Athar there. Teach me to dilly-dally on my replies.
Last edited on
Works great, Thanks guys.
You may want to take a look at getopt(), getopt_long(), getopt_long_only()
Topic archived. No new replies allowed.