2015-09-28 102 views
0

胡作非爲我有這樣的代碼:STRCMP 2個相同的字符串

#include <stdio.h> 
#include <string.h> 

int main() { 

    char s1[50], s2[50]; 

    printf("write s1:\n"); 
    fgets(s1, sizeof(s1), stdin); 

    printf("s2:\n"); 
    fgets(s2, sizeof(s2), stdin); 

    printf("The concatenation of the two strings: %s\n", strcat(s1, s2)); 

    if(strcmp(s2, s1) < 0) { 
    printf("s2 is shorter than s1.\n"); 
    } else if(strcmp(s2, s1) > 0) { 
    printf("s2 is longer than s1.\n"); 
    } else { 
    printf("strings are equal.\n"); 
    } 

    return 0; 
} 

的問題是,當我寫2個像ABC或任何相同的字符串,返回的strcmp「S2比S1更短。」

這是正常的輸出還是我做錯了什麼?如果是這樣,在哪裏?

或strcat使字符串不相等?可以做任何事情嗎?

謝謝

+0

請參閱[strcmp](http://www.cplusplus.com/reference/cstring/strcmp/)部分的返回值。返回的值僅與第一個差異有關(與總長比較無關)。如果要比較字符串長度,請使用[strlen](http://www.cplusplus.com/reference/cstring/strlen/).. – amdixon

+0

是的。 strcat在代碼中時返回一個非零數字。當我評論它,然後strcmp返回0 – zeeks

+1

s1 =「abcabc」和s2 =「abc」,比較使得s2比s1短。 –

回答

4

你在比較之前做

strcat(s1, s2) 

。這將修改字符串s1所以字符串將不會相等

1

你在做strcmp之前正在做一個strcat。 strcat將s2連接到s1

1

Strcmp根據字符串內容的值(類似於字典順序,如果你喜歡,但不完全是這樣)比較字符串,而不是根據它們的長度。

例如: 「ABC」> 「ABB」

1

嘗試用

printf("The two strings are: '%s' and '%s' and their concatenation: '%s'\n", 
    s1, s2, strcat(s1, s2)); 

替換

printf("The concatenation of the two strings: %s\n", strcat(s1, s2)); 

然後讀取的strcat的描述。

如果這沒有幫助,請用%p替換%s序列。 (可能需要閱讀printf文檔中的%p格式說明符的說明。)

相關問題