下面的代碼是在我的頭文件: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