qq_45735316 2019-12-03 13:03 采纳率: 94.1%
浏览 345
已采纳

(重现strcmp函数)为什么结果不是1?是字符串的输入有问题吗?

#include
#include
#define M 10
/*238-5.编写比较字符串的函数(重现strcmp函数)*/
/* run this program using the console pauser or add your own getch, system("pause") or input loop /
int Strcompare(char *s1,char *s2)
{
char *ss1,*ss2;
ss1=s1;
ss2=s2;
while(
(ss1++)==*(ss2++)&&*(ss1++)!='0'&&*(ss2++)!='0')
{

}

return *s1-*s2 ;

}
int main(int argc, char *argv[])
{
char *s1,*s2,str1[M],str2[M];
int i=0,j=0;
int a;
while(((str1[i++]=getchar())!='\n')&&((str2[j++]=getchar())!='\n'));
s1=str1;
s2=str2;
a=Strcompare(s1,s2);
printf("%d",a);

return 0;

}
图片说明


  • 写回答

2条回答

  • threenewbee 2019-12-03 17:30
    关注

    我调试了下,你的输入就不对,看下面的程序

    #include <stdio.h> 
    #include <stdlib.h> 
    #define M 10
    /*238-5.编写比较字符串的函数(重现strcmp函数)*/
    
    int Strcompare(char *s1,char *s2)
    {
        while (1)
        {
            if (*s1 == 0 && *s2 == 0) return 0;
            if (*s1 == 0) return - 1;
            if (*s2 == 0) return 1;
            if (*s1 != *s2) return *s1 - *s2;
            s1++;
            s2++;
        }
        return 0;
    }
    int main(int argc, char *argv[])
    {
        char *s1,*s2,str1[M],str2[M];
        int i=0,j=0;
        int a;
        //while(((str1[i++]=getchar())!='\n')&&((str2[j++]=getchar())!='\n'));
        scanf("%[^\n]", str1);
        fflush(stdin);
        scanf("%[^\n]", str2);
        s1=str1;
        s2=str2;
        a=Strcompare(s1,s2);
        printf("%d",a);
        return 0;
    }
    
    

    用换行来输入
    以下是程序运行:
    a
    b
    -1Press any key to continue . . .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果