【问题标题】:If statements in my C code are doing the exact opposite of the conditions?如果我的 C 代码中的语句与条件完全相反?
【发布时间】:2016-03-27 19:10:58
【问题描述】:

所以我正在比较两个字符串,而我的代码正在做与它应该做的完全相反的事情。我无法切换我的 printf 语句,因为那样那也是错误的。如果我输入第一个长度为 5 的字符串和第二个长度为 6 的字符串,它会说字符串 1 比字符串 2 大,而恰恰相反。
这是我所拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    char str1[100], str2[100];

      printf("enter the first string :");
      scanf("%s", &str1);
      printf("enter the second string :");
      scanf("%s", &str2);

     if(strcmp(str1,str2)==0){
        printf("the strings are equal\n");
     }
     else if(strcmp(str1,str2)<0){ 
        printf("string 1 is less than string 2\n");
     }
     else{
        printf("string 1 is greater than string 2\n");
     }
    return 0;
}

【问题讨论】:

  • Strcmp 不比较长度:它比较字母排序顺序。

标签: string if-statement strcmp


【解决方案1】:

strcmp 不比较字符串的长度。它比较字符,直到找到两个不相同的字符,然后根据哪个字符串在字母表中具有该字符,返回一个负数或正数。如果一个字符串用完(“Hello”与“Hell”),那么较短的字符串首先出现。如果它们相同,则结果为 0。

例如,“xyz”>“abcde”,因为 x 在 a 之后。

【讨论】:

    【解决方案2】:

    Strcmp 根据字母顺序比较字符串。 要比较字符串的长度,只需将 strcmp() 替换为 strlen()。

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多