下面的代码在我的头文件中:
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/