下面的代码是在我的头文件:2测试失败与我的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文件
我一直在试图解决这个问题但不知道如何。
它从来没有真正比较一个字符是否比其他更大或更小。这就像主要部分。 – chris
我担心简单地修复你的代码,因为我很确定这是一个家庭作业问题。如果你跟踪你的执行情况,你应该能够清楚地看到断言失败的原因。提示:它与来自'mystrcmp'的返回值有关系吗? – Unsigned
你想只比较长度,还是试图实现一个实际的strcmp-esque函数?如果是后者,你从不比较单个字母。如果他们的长度不相等,你也总是返回-1,这不取决于哪一个更长。 – vroomfondel