2013-07-03 52 views
0

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

我一直在試圖解決這個問題但不知道如何。

+0

它從來沒有真正比較一個字符是否比其他更大或更小。這就像主要部分。 – chris

+2

我擔心簡單地修復你的代碼,因爲我很確定這是一個家庭作業問題。如果你跟蹤你的執行情況,你應該能夠清楚地看到斷言失敗的原因。提示:它與來自'mystrcmp'的返回值有關係嗎? – Unsigned

+0

你想只比較長度,還是試圖實現一個實際的strcmp-esque函數?如果是後者,你從不比較單個字母。如果他們的長度不相等,你也總是返回-1,這不取決於哪一個更長。 – vroomfondel

回答

5

strcmp被定義爲如果返回正值」第一「string大於」second「字符串,如果它們相等,則爲零值,如果」first「小於」second「字符串,則爲負值。因此,如果字符串不相等,則應決定哪一個是更大,然後返回相應的值

實現該操作的簡單方法是返回*s1 - *s2(也是r當它們相等時會減少0,作爲獎勵)。

0

您只有返回-10。閱讀這些斷言,他們爲什麼失敗?

此外,在第5行,你只需要檢查要麼*s1=='\0'*s2=='\0',因爲你知道他們是由於while條件相等。

2

那麼,在你的mystrcmp功能,我沒有看到那個地方返回正數,所以"Ruth""Gehrig之間的比較「總是會失敗。

0

正如其他人所說,strcmp應該返回正數和負數。

試試這個:

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

只是好奇,爲什麼你使用for循環而不是while循環? – Joe

+0

@Joe:因爲它更短。「while」更適合於當「counter」(控制變量)以非平凡的方式改變時('if(something){i ++;} else {i = nextValue();}'或類似的東西)。 – SigTerm

0

嗯......你mystrcmp功能不會失敗第二次測試。

http://ideone.com/ZcW02n

#include <iostream> 

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); 
} 

int main() { 
     std::cout << mystrcmp("","") << std::endl; 
     return 0; 
} 

output: 0