2016-04-26 62 views
0

您好我有這個代碼在這裏試圖詢問用戶有關的位置。當用戶輸入位置它只是說再見。我的代碼中有什麼錯?如果 - 其他程序

#include<stdio.h> 

int main() 
{ 

     char location[15]; 
     printf("1:Greencourt\n"); 
     printf("2:Corianthans\n"); 
     printf("3:Shop\n"); 
     printf("Enter a location\n"); 
     scanf("%s",location); 
     if(location=="Greencourt") 
     printf("Bisleri bottle cost 25 rupees\n"); 
     else 
     if(location=="Shop") 
     printf("Bisleri bottle cost 15 rupees\n"); 
     else 
     if(location=="Corianthans") 
     printf("Bisleri bottle cost 50\n"); 
     else 
     printf("Bye"); 

     return 0; 
} 

這裏是輸出

1:Greencourt 
2:Corianthans 
3:Shop 
Enter a location 

Shop 

Bye 
+0

更好地使用STRCMP值compaiting串 –

+1

由於標籤與C的問題++,我建議你使用'std :: string'而不是普通的char數組。 – soon

+0

請縮進您的代碼。 –

回答

3

你比較字符串(字符數組)你不能使用 '==' 操作。 您應該使用strcmp功能:

int strcmp(const char *str1, const char *str2) 

這樣:

if(strcmp(location,"Greencourt") == 0) 
+3

它可能應該是'if(!strcmp(location,「Greencourt」))',因爲如果字符串是「等於」,strcmp將返回0 –

+0

@EugeneAnisiutkin yes ,謝謝 – granmirupa

+0

注意,如果字符串相同,strcmp會回退0。因此,上面的答案並不完全正確,但它朝着正確的方向 – Nobby

1

它的更好,如果你比較使用strcmp()

+0

#include #include int main() { char location [16]; \t printf(「1:GT \ n」); \t printf(「2:Cori \ n」); \t printf(「3:Shop \ n」); \t printf(「Enter a location \ n」); scanf(「%s」,location);如果(strcmp(location,「GT」)== 0) printf(「Bisleri bottle cost 25 rupees \ n」); else if(strcmp(location,「Shop」)== 0) \t printf(「Bisleri bottle cost 15 rupees \ n」); else if(strcmp(location,「Cori」)== 0) \t printf(「Bisleri bottle cost 50 \ n」); else printf(「Bye」); return 0; } \t 〜/ MY_C $ ./a.out 1:GT 2:Cori 3:Shop – Neeld