c++command-line-arguments

What is wrong with my reading of command line arguments?


I am writing a program for working with functions and graphs, but that is beside the point. In my int main() I just look at the command line arguments, and then match them up to the expected result.

int main(int argc, char* argv[]) {
    // Draw a plot from a file
    if (argv[1] == "draw" && std::string(argv[2]).substr(std::string(argv[2]).size() - 4) == ".txt") {
        return draw(argv[2], argv[3]);
    }

    // Draw a plot from a function
    else if (argv[1] == "draw") {
        plot(argv[2], std::stoi(argv[3]));
        return 0;
    }

    // Get the y value for given x and function
    else if (argv[1] == "get_y") {
        std::cout << node(std::stod(argv[2]), argv[3]) << std::endl;
        return 0;
    }

    // Find intersection of functions in a file
    else if (argv[1] == "matches") {
        if (argc == 4) for (std::pair<double, double> m : matches(argv[2], std::stoi(argv[3]), 0.1))                std::cout << m.first << ": " << m.second << std::endl;
        if (argc == 5) for (std::pair<double, double> m : matches(argv[2], std::stoi(argv[3]), std::stod(argv[4]))) std::cout << m.first << ": " << m.second << std::endl;
        return 0;
    }

    // Help
    else if (argv[1] == "help") {
        std::cout
            << "Commands for graph:\n"
            << "    Draw a graph for one or multiple functions:      graph draw <file.txt> <range>\n"
            << "                                                     graph draw <function> <range>\n"
            << "    Find y value for a given x using given function: graph get_y <x> <function>\n"
            << "    Find intersections between multiple functions:   graph matches <file.txt> <range> [<precision>]\n";
        return 0;
    }

    else {
        std::cerr << "Error: Invalid command or arguments. Use 'graph help' for more information." << std::endl;
        return 1;
    }
}

However, when I try to run it from cmd, it always returns "Error: Invalid command or arguments. Use 'graph help' for more information.". Please, somebody help me understand how exactly should I check the command line arguments. (Keep in mind that I am a newbie, so please explain it like I am 5 years old)


Solution

  • The argv[] is an array of pointers to character(s), e.g. char *.

    The expression if (argv[1] == "Hello") is comparing a pointer to a character (argv[1]) to the address of a character array, "Hello". So this expression is comparing pointers not array contents.

    When using C-Style strings, or nul terminated arrays of characters, there are a bunch of functions to help you out: strcmp, strcpy, strcat, etc. Remember that a C-Style string is an array of characters terminated by a nul character ('\0').