2016-07-13 231 views
-3
#include <stdio.h> 
#include <stdlib.h> 

//CALLBACKS 
void infoCallback(){ 
    system("cheese"); 
} 
void wgetCallback(char *website){ 
    if(website == NULL) 
     printf("\nSITIO WEB NO INGRESADO!\n"); 
    else{ 
     printf("%s \n", website); 
     system("echo making wget success"); 
    } 
} 

int main(int argc, char *argv[]){ 
    printf("\tAUTO-BASH\n"); 

    printf("%s \n", argv[1]); 

    if(argv[1] == "-w"){ 
     wgetCallback(argv[2]); 
    } 
    else if(argv[1] == "-i"){ 
     infoCallback(); 
    } 
    else{ 
     printf("\nsos un noob\n"); 
    } 
} 

它不會做我想要的....如果我寫-w,它去別的。 ... 我想打一個開關(任何類型){ 案「??」: 但我不知道爲什麼我不能這樣做。字符串比較與==

+0

檢查的argv的值[1],也許你需要將它轉換爲字符串 – Nezir

+0

'「-w」'是一個常數。 'argv [1]'是一個變量。指向變量的指針並不等於指向常量的指針,因爲它們不可能指向相同的東西,因爲某些變量既不能是變量也不能是常量。 –

+1

@David Schwartz技術上不同意「不等於」。儘管不適用於'argv []',請考慮'char * s =「-w」;如果(s ==「-w」)...'。在這種情況下,比較可能是正確的,因爲代碼可能會將''-w''摺疊到相同的地址 - 否則它可能不會。 IAC,不是一個好的編程習慣。 – chux

回答

2

你不能用==比較C字符串。使用strcmp

if(strcmp(argv[1],"-w") == 0) 
3
  1. 比較字符串使用strcmp
  2. 開關做只適用於序型
0

你也不會在C與==比較字符數組和C不支持operator overloading。你必須使用standard library functionstrcmp()或使自己的功能。

例如,

if (!strcmp(argv[1],"-w")) 

但是你可以使用==操作比較兩個字符。你可以試試這個。

#include <stdio.h> 

void infoCallback() 
{ 
    printf("cheese\n"); 
} 

void wgetCallback() 
{ 
    printf("website\n"); 
} 

int singleCharOpt(char *opt) 
{ 
    if (*(opt+1) != '\0') { 
     printf("Not a Valid Single Character Option\n"); 
     return -1; 
    } 
    if(*opt == 'w') { 
     wgetCallback(); 
    } else if(*opt == 'i') { 
     infoCallback(); 
    } else { 
     printf("Unknown Option\n"); 
    } 
    return 0; 
} 


int main(int argc, char *argv[]) 
{ 
    /* Do Something */ 
    printf("Hello options\n"); 

    if (argc <= 1) 
     return 0; 
    int i; 
    for (i=1; i<argc; i++) { 
     printf("Option: %s\n", argv[i]); 
     char *opt = argv[i]; 

     int result = (*opt == '-') ? singleCharOpt(++opt) : -1; 

     if (result) 
      printf("Wrong Option\n"); 
    } 
    return 0; 
} 
1

退後一會兒。在C中,什麼是字符串

是由封端的字符的連續序列,並且包括第一個空字符。
C11§7.1.11

不是指針,而不是地址,而是字符序列這樣的陣列或一個字符串文字

比較字符串,代碼需要這些陣列的內容進行比較。使用strcmp()

// compares pointers - not a string compare 
if(argv[1] == "-w") { 

// compares content - a string compare 
if (strcmp(argv[1], "-w") == 0) { 

argv[1] == "-w"比較指針,而不是它們指向的內容。

strcmp(argv[1], "-w")需要的argv[1],一個char *值和字符串字面"-w"的地址,也char *,並使用這些2至開始時遇到空字符的區別,直到比較char -by- char