主要论点处理的问题

Issue with main arguments handling

本文关键字:问题 处理      更新时间:2023-10-16

我无法将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 %sn",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"

我的代码怎么了?

无法与==进行比较,使用strcmp:

if (strcmp(argv[i], "hello") == 0)

您必须进行#include <string.h>

每当您使用argv [i] ==" hello"时,操作员" ==" donot将字符串作为操作数,因此在编译器中,编译器将指针与argv [i]进行比较恒定字符串" hello"的指针总是false,因此您获得的结果是正确的,要比较字符串文字使用SRTCMP函数。 int strcmp(const char *s1,const char *s2);比较了两个字符串S1和S2。它返回一个整数小于,等于或大于零,如果发现S1的数量小于匹配或大于S2。

在此语句中

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

您比较指针,因为字符串文字被隐式转换为指向其第一个字符的const char *(或char *)。由于两个指针具有不同的值,因此表达式始终是错误的。您必须使用标准的C函数strCMP。例如

if( std::strcmp( argv[i], "hello" ) == 0 )

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