Reputation: 79
The code below is in my header file:
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);
}
The problem is when I run it my main.cpp says it fails 2 test
Below is an excerpt from my 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??
}
Note: I cannot change the .cpp file
I have been trying to fix this issue but do not know how.
Upvotes: 0
Views: 736
Reputation:
Hmmm... your mystrcmp function does not fail the second test.
#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
Upvotes: 0
Reputation: 26439
As other people said, strcmp is supposed to return positive and negative numbers.
Try this instead:
int mystrcmp(const char *s1, const char *s2){
for(;*s1 && *s2 && (*s1 == *s2); s1++, s2++){}
return *s1 - *s2;
}
Upvotes: 0
Reputation: 129524
strcmp
is defined to return a positive value if the "first" string is greater than the "second" string, a zero value if they are equal and a negative value if the "first" is less than the "second" string. So if the strings are not equal, you should decide which one is greater and then return the appropriate value.
An easy way to achieve that is to return *s1 - *s2
(which also returns 0 when they are equal, as a bonus).
Upvotes: 5
Reputation: 9270
Well, in your mystrcmp
function, I see no spot where you return a positive number, so the compare between "Ruth"
and "Gehrig
" will always fail.
Upvotes: 2
Reputation: 9936
You only ever return -1
or 0
. Read the assertions, why are they failing?
Also, on line 5, you only need to check either *s1=='\0'
or *s2=='\0'
, since you know they're equal due to the while
condition.
Upvotes: 0