问题与主要论据处理 [英] Issue with main arguments handling

查看:187
本文介绍了问题与主要论据处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法与为const char * 字符串比较的main()参数。

I can't compare main() arguments with const char* strings.

简单code用来说明:

Simple code for explaining:

#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 。当我尝试执行它,我看到了接下来的事情:

Simple compile g++ test.cpp. When I try execute it, I see next thing:

>./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"

请告诉我错了我的code?

Whats wrong with my code?

推荐答案

在此声明

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

你比较指针,因为文字字符串隐式转换为const char *(或字符* C语言)指向它的第一个字符。由于两个指针具有不同的值除权pression永远是假的。您必须使用标准的C函数strcmp来代替。例如:

you compare pointers because the string literal is implicitly converted to const char * (or char * in C) that points to its first character. As the two pointers have different values the expression is always false. You have to use standard C function strcmp instead. For example

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

要使用此功能,您应该包括头&LT; CString的&GT; (在C ++)或&LT;文件string.h&GT; (C语言)。

To use this function you should include header <cstring>(in C++) or <string.h> (in C).

这篇关于问题与主要论据处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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