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.
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).