views:

303

answers:

6

Alright, I'm trying to get arguments to work properly with a small test application. My code is below. I'm not too experienced at C++, so I'm not sure why when I launch test with -print (or --print) it automatically states "Not a valid option" and then finishes up.

#include <iostream>

int main(int argc, char* argv[])
{
    int option;
    option = 1;
    char* argument;
    argument = argv[option];
    while (option < argc)
    {
        if (argument == "-print")
        {
            std::cout << "Printing Extra Text";
        }
        else
        {
            std::cout << "Not a valid option" << std::endl;
        }
        option++;
    }
    std::cout << "Printing normal text" << std::endl;
    return 0;
}

Am I doing this right? Thanks in advance.

+12  A: 

You're comparing the memory address of the string "-print" to the memory address of argument. This won't work! Use strcmp() to compare string values. Instead of:

if (argument == "-print")

do

if (strcmp(argument, "-print") == 0)
Gerald Kaszuba
+1  A: 
if (argument == "-print")

you can not compare strings like this!

Use strcmp() to compare strings.

Stefan
+8  A: 

The following line is at fault:

if (argument == "-print")

Here you're comparing pointers, not string values. Replace with:

if (strcmp(argument, "-print") == 0)

C/C++ behave differently than Java or C# regarding string handling. Strings are not a native type or object but just glorified pointers to arrays of chars.

Alternatively, and if your option list becomes more complicated, consider using a dedicated option parsing library such as Boost's Program_options. It will handle all the aspects including validation and user messages.

fbonnet
+2  A: 

It's been a while that I programmed in C++, but shouldn't one just use

std::string argument;

and then the comparison with == would work?

Ulrich Gerhardt
+1  A: 

Your question states you also want to test for --print (two dashes), but your code doesn't check for that.

Also, you assign argument outside the loop, you will want to do that inside the loop otherwise you'll only be testing argument #1 each time around the loop.

Steve Folly
+1  A: 

There is another problems, when you read the argument. (with all necessary changes)

int main(int argc, char* argv[])
{
    int option;
    option = 1;
    char* argument;
    while (option < argc)
    {
        argument = argv[option];
        if (strcmp(argument, "-print") == 0)
        {
            std::cout << "Printing Extra Text";
        }
        else
        {
            std::cout << "Not a valid option" << std::endl;
        }
        option++;
    }
    std::cout << "Printing normal text" << std::endl;
    return 0;
}
DrHazzard