我无法将main()参数与const char*字符串进行比较。

简单代码说明:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int i;
  if(argc>1)
  {
    for (i=1;i<argc;++i)
    {
      printf("arg[%d] is %s\n",i,argv[i]);
      if(argv[i]=="hello")
        printf("  arg[%d]==\"hello\"\n",i);
      else
        printf("  arg[%d]!=\"hello\"\n",i);
    }
  }
  return 0;
}

简单编译g++ test.cpp。当我尝试执行它时,我看到下一件事:
>./a.out hello my friend
arg[1] is hello
  arg[1]!="hello"
arg[2] is my
  arg[2]!="hello"
arg[3] is friend
  arg[3]!="hello"

我的代码有什么问题?

最佳答案

在此声明中

if(argv[i]=="hello")

您比较指针是因为字符串文字会隐式转换为指向第一个字符的const char *(或C中的char *)。由于两个指针具有不同的值,因此表达式始终为false。您必须改为使用标准C函数strcmp。例如
if( std::strcmp( argv[i], "hello" ) == 0 )

要使用此功能,您应该包括头<cstring>(在C++中)或<string.h>(在C中)。

关于c++ - 主要参数处理问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21454739/

10-15 06:00
查看更多