c++ - 2 我的 strcmp 函数测试失败

标签 c++ strcmp

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

int mystrcmp(const char *s1, const char *s2) // strcmp function
{
    while(*s1 == *s2)
    {
        if(*s1 == '\0' || *s2 == '\0')
            break;

        s1++;
        s2++;
    }

    if(*s1 == '\0' && *s2 == '\0')
        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,作为奖励)。

关于c++ - 2 我的 strcmp 函数测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459479/

相关文章:

c++ - 计算匹配数

c++ - xalan 和 xerces 的多个版本

c - 对于矩阵来说,这是正确的类型和逻辑吗?

c - 拼写检查程序问题

c++ - strcmpi 整数,无转换错误

c++ - 在 Qt Creator 新项目向导的自定义模板中创建类?

c++ - 在单独分配的堆栈上运行函数

c - 请帮助我了解 "strcmp"

c - C 中的 strcmp 和 void 指针

c++ - C++宏中的字符串修改