Checking argv[] against a string? (C++)

前端 未结 5 708
情歌与酒
情歌与酒 2020-12-28 15:05

So I\'m attempting to check the arguments that I\'m inputting into my program, and one of them is either the word \"yes\" or \"no\", entered without the quotes.

I\'

5条回答
  •  醉梦人生
    2020-12-28 15:26

    You're comparing pointers. Use strcmp, or std::string.

    int main(int argc, char * argv[]) {
    
      if (argv[1] == "yes"); // Wrong, compares two pointers
      if (strcmp(argv[1], "yes") == 0); // This compares what the pointers point to
      if (std::string(argv[1]) == "yes"); // Works fine
      if (argv[1] == std::string("yes")); // Works fine
    
      // Easy-mode    
      std::vector args(argv, argv+argc);
      for (size_t i = 1; i < args.size(); ++i) {
          if (args[i] == "yes") {
              // do something
          }
      }
    
    }
    

提交回复
热议问题