主要参数处理问题

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

简单的代码解释:

 #include  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 ) 

要使用此函数,您应该包含头 (在C ++中)或 (在C中)。

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

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

你必须#include

无论何时使用argv [i] ==“hello”,运算符“==”都不要将字符串作为其操作数,因此实际上编译器会将指向argv [i]的指针与指向常量字符串“Hello”的指针进行比较。 false,因此你得到的结果是正确的,比较字符串文字使用srtcmp函数。 int strcmp(const char * s1,const char * s2); 比较两个字符串s1和s2。 如果找到s1,则它返回小于,等于或大于零的整数,小于,匹配或大于s2。

Interesting Posts