是否针对字符串检查argv []? (C ++) [英] Checking argv[] against a string? (C++)

查看:158
本文介绍了是否针对字符串检查argv []? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图检查要输入到程序中的参数,其中之一是单词 yes或 no,输入时不带引号。

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.

我正在测试等效性(if(argv [n] == yes)),但每次输入时,它似乎都返回false,实际上,是的(当我输出时,它确认了这一点)。我在这里想念我做错了什么?
如果我正确理解argv [n]返回的字符串以null终止,那么它应该允许我这样做。

I'm trying to test equivalency ( if (argv[n] == "yes") ) but that seems to be returning false every time when the input is, in fact, yes(When I output it it confirms this). What am I missing here that I'm doing improperly? If I understand properly argv[n] returns a cstring that is null-terminated, so it should allow me to do this.

推荐答案

您正在比较指针。使用strcmp或std :: string。

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<std::string> args(argv, argv+argc);
  for (size_t i = 1; i < args.size(); ++i) {
      if (args[i] == "yes") {
          // do something
      }
  }

}

这篇关于是否针对字符串检查argv []? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆