2014-01-30 76 views
1

我無法比較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" 

我的代碼有什麼問題?

+0

這將在C++中工作過,如果你要使用'標準::矢量 ARGS(的argv,argv的+ ARGC)' - 在C++'的std :: string'確實有一個令人吃驚的'運營商==' – MSalters

回答

1

在這份聲明中

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

你比較指針,因爲字符串文字是隱式轉換爲const char *(或C中的char *),指向它的第一個字符。由於這兩個指針有不同的值,表達式總是爲false。您必須改用標準的C函數strcmp。例如

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

要使用該功能,你應該包括報頭<cstring>(在C++)或<string.h>(在C)。

2

字符串不能與==相比,使用strcmp

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

你必須#include <string.h>

+0

你受歡迎的 ;) –

2

無論何時使用argv [i] ==「hello」,運算符「==」都不會將字符串作爲操作數,因此實際上編譯器會將指向argv [i]的指針與指向常量字符串「Hello 「這總是假的,因此你得到的結果是正確的,比較字符串文字使用srtcmp函數。 int strcmp(const char * s1,const char * s2); 比較兩個字符串s1和s2。如果找到s1,它將分別返回小於,等於或大於零的整數,以小於,匹​​配或大於s2。