0

I am trying to make a CLI app in C++. This is my first time coding in C++.

I have this c++ code:

#include <iostream>
// using namespace std;

static void help(std::string argv)
{
    std::cerr << "Usage:" << argv << " [options]\n"
        << "Options:\n"
        << "-h (--help): Displays this help message.\n"
        << "-o (--output=[output file]): Specifies the output file.\n"
        << "-p (--ports=[ports]) Sets the ports to scan.\n"
        << std::endl;
}

int main(int argc, char** argv)
{
    if (argc > 1)
    {
        std::cout << argv[1] << "\n";
        if (argv[1] == "-h" || argv[1] == "--help")
        {
            help(argv[0]);
            return 0;
        }
    } 
    else 
    {
        std::cout << "No arguments were given" << "\n";
    };
};

// g++ -o cli main.cpp

It works! When I compile it, it successfully outputs No arguments were given, but when I run cli -h, I can see argv[1] is -h, but nothing is outputted.

What did I do wrong?

divinelemon
  • 1,925
  • 2
  • 23
  • Do not reinvent the wheel [boost::program_options](https://www.boost.org/doc/libs/1_58_0/doc/html/program_options.html) or [argparse](https://github.com/hbristow/argparse) or anything else. – Marek R Nov 09 '21 at 15:42
  • @MarekR Thanks so much! For this question, it doesn't help, but I will certainly start using those programs. Thanks again! – divinelemon Nov 09 '21 at 15:46

1 Answers1

1

In your string comparison, argv[1] is a C string: a null-terminated char array. You cannot compare these with == and get the result you expect. If, however, you assign it to a std::string you can compare it with "-h" and "--help" the way you want.

std::string arg1 = argv[1];
if (arg1 == "-h" || arg1 == "--help") {
    help(argv[0]);
    return 0;
}

Alternatively you could use std::strcmp to compare C strings without creating a new std::string. In order to do this, you'll need #include <cstring>.

if (std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") == 0) {
    help(argv[0]);
    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42