2015-09-28 74 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格式说明符的说明。)