2013-07-03 47 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