0

I have tried to create a C++ argument parsing system like it is in Python (--tag or -t and later the value), but my code will not work. I have doubled and tripled checked it and nothing seems to be wrong with it.
Basically, what it does is it gets the arguments and loops through them all until it finds one that is either --dict or -d and then the argument++ is saved in the dict variable.

Here's the code:

#include <iostream>
#include <string>

int main (int argc, char* argv[]) {
    for (int i=0; i<argc; i++) {
        std::cout<<i<<" - "<<argv[i]<<std::endl;
        if (argv[i] == "--dict" || argv[i] == "-d") {
            std::string dict = argv[i++];
            std::cout<<"Dictionary: "<<dict<<std::endl;
        }
    }
    return 0;
}
tzrm
  • 513
  • 1
  • 8
  • 14
  • 2
    If you want to compare C-style strings, you need to use strcmp(). –  Feb 25 '18 at 23:18
  • 1
    `if (argv[i] == "--dict" || argv[i] == "-d")` does not work because it compares two pointers. Use `std::strcmp` instead. I suspect there are many questions at SO about that. – R Sahu Feb 25 '18 at 23:18
  • You cannot compare strings by comparing pointers. You need something like `std::strcmp`. – Kerrek SB Feb 25 '18 at 23:18
  • If you are not trying to code argument parsing for exercise, you could simply use the [GNU getopt](https://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Getopt.html). – spider Feb 25 '18 at 23:21
  • _"my code will not work"_ _"nothing seems to be wrong with it"_ An interesting deduction! – Lightness Races in Orbit Feb 26 '18 at 00:00
  • haha true. Well I did actually realize I'm comparing two pointers and fixed that, but now everytime I try to declare a variable with the value of std::string(stgv[i++]) instead of storing the i++ value it stores the i. – Michael Dimopoulos Feb 26 '18 at 09:49

1 Answers1

1

argv[i] == "--dict" is comparing pointers (which will never match). You can compare the pointer contents using strcmp or convert one to a string and use ==

// Compare using strcmp
if (strcmp(argv[i], "--dict") == 0 || strcmp(argv[i], "-d") == 0)

// Compare using strings
std::string arg(argv[i]);
if (arg == "--dict" || arg == "-d") {
John3136
  • 28,809
  • 4
  • 51
  • 69