help with pointers

I am trying to write a function that will do the same thing as strcmp (string comparison) does. I am also adding something to make this case sensitive


Maybe this will help. This is what it is written out.:
strcmp takes two cstrings and compares character by character until
it finds two characters that don't match or it reaches the end of both cstrings.

It will return a negative number if the character in the first cstring
comes before the character in the second

It will return a positive number if the character in the first cstring
comes after the character in the second

It will return 0 if they're the same

Here are some examples:

cout << strcmp( "hello", "help" ) << "\n"; // negative (-1)
cout << strcmp( "help", "hello" ) << "\n"; // positive (1)
cout << strcmp( "help", "help" ) << "\n"; // 0

This should not affect the results due to the "tolower" being applied.
cout << strcmp( "aardvark", "Zebra" ) << "\n";

I think I am I pritty close but no matter what words I put in it always returns 1. I don't know whats wrong.






#include<iostream>
using std::cout;
using std::cin;

int mystrcmp ( const char * s1, const char * s2 )
{

while (true)
{
if (!(*s1) && !(*s2)) return 0;
if (!(*s1)) return -1;
if (!(*s2)) return 1;

if (tolower(*s1) <= tolower(*s2)) return -1;
if (tolower(*s2) <= tolower(*s1)) return 1;

++s1;
++s2;
}
}

int main()
{

const int SIZE = 100;
char word1[SIZE]=" ";
char word2[SIZE]=" ";
cout << "enter 2 words \n";
cin.getline( word1, SIZE );
cin.getline( word2, SIZE );
cout << mystrcmp( word1, word2 );

return 0;
}
1
2
if (tolower(*s1) <= tolower(*s2)) return -1;
if (tolower(*s2) <= tolower(*s1)) return 1;


Are you sure you want <= there?

Think about it. What is the desired behavior if tolower(*s1) == tolower(*s2)?
thanks that fixed those 2 but if its the same word it still doesn't return a 0.
Your logic is not quite right!

Set a break point on the return (-1) when you test with two identical strings.

Andy
Last edited on
Topic archived. No new replies allowed.