int main()
{
char text[128];
cin.getline(text, 128);
char abc[]="ABC";
if (myStrCmp(text, abc)==0)
{
cout<<"Your string equals ABC"<<endl<<endl;
}
else
{
cout<<"Your string does not equal ABC"<<endl<<endl;
}
}
int myStrCmp(constchar text[], constchar abc[])
{
int i;
int res;
int temptext,tempabc;
for(i = 0; abc[i] != '\0';i++)
{
temptext=text[i];
tempabc=abc[i];
res=tempabc-temptext;
if (res!=0)
return 1;
}
return 0;
}
The problem is if the Input has longer length such as ABCD, since it only checked the string length of ABC, it won't know there is a 4th one behind,
The result will be "Your string equals ABC", which is wrong.
int myStrCmp(constchar text[], constchar abc[])
{
int i = 0;
while (text[i] && abc[i] && text[i] == abc[i])
++i;
return text[i] == abc[i] ? 0 : (text[i] > abc[i] ? 1 : -1);
}
the while loop is used to skip all of the similar characters, and stop if it gets to the end of any string. Then simply return the comparison of the current different chars.
Ex:
"Ab"
"ABC"
int i will stop at 1, and myStrCmp will return 1 because 'b' > 'B'
"ABCdE"
"ABCDE"
int i will stop at 3, and myStrCmp will return 1 because 'd' > 'D'
"AB"
"ABC"
int i will stop at 2, and myStrCmp will return -1 because '\0' < 'C'
"ABC"
"ABC"
int i will stop at 3, and myStrCmp will return 0 because '\0' == '\0'
"ABCD"
"ABC"
int i will stop at 3, and myStrCmp will return 1 because 'D' > '\0'
What I was aiming for when I made the earlier suggestion:
1 2 3 4 5 6 7 8 9
int i = 0 ;
while ( text[i] != '\0' && abc[i] != '\0' )
{
if ( text[i] != abc[i] )
break ;
++i ;
}
return text[i] == abc[i] ;
Assuming, of course, as your original code indicated the function should return true if they're equal and false if they're not as opposed to the return value required by the C library for the analogous function.
It's really old (1984), but it is written by the guys who invented C. It has some really good reference material for the C language.
HEre is some of their code:
1 2 3 4 5 6 7 8 9
/* strcmp: return <0 if s<t, 0 if s==t, >0 if s>t */
int strcmp(char *s, char *t)
{
int i;
for (i = 0; s[i] == t[i]; i++)
if (s[i] == '\0')
return 0;
return s[i] - t[i];
}
This is the pointer version:
1 2 3 4 5 6 7 8 9 10 11 12
/* strcmp: return <0 if s<t, 0 if s==t, >0 if s>t */
int strcmp(char *s, char *t)
{
for ( ; *s == *t; s++, t++)
if (*s == '\0')
return 0;
return *s - *t;
}
Hope this is not cheating too much !!!!
I should point out that that book is written with ANSI C, there have been quite a few changes to the standard since then, but their code should still work.