c++ - 主要参数处理问题

标签 c++ c program-entry-point args

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

我的代码有什么问题?

最佳答案

字符串不能与== 进行比较, 使用 strcmp :

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

你必须 #include <string.h>

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

相关文章:

c++ - 带有控制台输出的 Qt GUI 应用程序 - 在 Windows 上正常启动时隐藏控制台

c++ - Visp 库 - 如何调整图像大小

c++ - 科学模拟中适当的类(class)成员访问

c - 快板显示奇怪的腐败视觉效果

c - 斐波那契数列之和

java - 错误 : could not find or load main class <class Name>

c++ - fanotify - 内核 5.1 中引入的新标志的问题

c - 读入每行包含多个元素的文本文件

c# - 多个主要功能

.net - 我的 VB.NET 解决方案不包含 Main 函数