2我的strcmp函数测试失败

2 Failed test with my strcmp function

本文关键字:测试 失败 函数 strcmp 我的      更新时间:2023-10-16

下面的代码在我的头文件中:

int mystrcmp(const char *s1, const char *s2) // strcmp function
{
    while(*s1 == *s2)
    {
        if(*s1 == '' || *s2 == '')
            break;
        s1++;
        s2++;
    }
    if(*s1 == '' && *s2 == '')
        return (0);
    else
        return (-1);
}

问题是当我运行它时,我的main.cpp说它没有通过2次测试

以下是我的main.cpp摘录:

void testmystrcmp(void)
{
   int iResult;
   iResult = mystrcmp("Ruth", "Ruth");
   ASSURE(iResult == 0);
   iResult = mystrcmp("Gehrig", "Ruth");
   ASSURE(iResult < 0);
   iResult = mystrcmp("Ruth", "Gehrig");
   ASSURE(iResult > 0);  // right here mystrcmp fails the test
   iResult = mystrcmp("", "Ruth");
   ASSURE(iResult < 0);
   iResult = mystrcmp("Ruth", "");
   ASSURE(iResult > 0);
   iResult = mystrcmp("", "");
   ASSURE(iResult == 0); // it also fails the test here but why??
}

注意:我无法更改.cpp文件

我一直在努力解决这个问题,但不知道如何解决。

strcmp被定义为,如果"第一个"字符串大于"第二个"字符串,则返回正值;如果它们相等,则返回零值;如果"第一"字符串小于"第二"字符串,返回负值。因此,如果字符串不相等,您应该决定哪个更大,然后返回适当的值。

实现这一点的一个简单方法是返回*s1 - *s2(当它们相等时,也会返回0作为奖励)。

好吧,在您的mystrcmp函数中,我看不到您返回正数的地方,所以"Ruth""Gehrig之间的比较"总是会失败。

您只能返回-10。阅读这些断言,它们为什么失败了?

此外,在第5行,您只需要检查*s1==''*s2=='',因为您知道它们由于while条件而相等。

正如其他人所说,strcmp应该返回正数和负数。

试试这个:

int mystrcmp(const char *s1, const char *s2){
    for(;*s1 && *s2 && (*s1 == *s2); s1++, s2++){}
    return *s1 - *s2;
}

嗯。。。您的mystrcmp函数在第二次测试中没有失败。

http://ideone.com/ZcW02n

#include <iostream>
int mystrcmp(const char *s1, const char *s2) // strcmp function
{
    while(*s1 == *s2)
    {
        if(*s1 == '' || *s2 == '')
            break;
        s1++;
        s2++;
    }
    if(*s1 == '' && *s2 == '')
        return (0);
    else
        return (-1);
}
int main() {
        std::cout << mystrcmp("","") << std::endl;
        return 0;
}
 output: 0