-2

Normally in C++ I would compare command line options as follows:

#include <string>

int main(int argc, char* argv[])
{
  if (std::string(argv[1]) == "-h") /*Handle -h option*/
  return 0;
}

This works just fine. But is there a way to do something similar in C?

YG-cpu
  • 37
  • 3

2 Answers2

0

This is just your code converted to C. As C doesn't have the type std::string you have to use character arrays. Those are compared with strcmp.

int main(int argc, char *argv[]) {
    if (strcmp(argv[1], "-h") == 0) /*Handle -h option*/
    return 0;
}
Bananenkönig
  • 547
  • 4
  • 12
0

You want to #include <string.h> and use strcmp() as in

if (strcmp(argv[1], "-h") == 0) {
    // whatever
}

Or, if you prefer to do it "by hand" with no calls into the C standard library

if ((argv[1][0] == '-') && (argv[1][1] == 'h') && (argv[1][2] == '\0')) {
    // whatever
}
pmg
  • 106,608
  • 13
  • 126
  • 198