I'm currently taking a class and the instructor told us to use the strcmp function whenever we needed to compare strings, something like...
if(strcmp(string, string) ==0)
Even though I tried... if (string == string)
and worked, the teacher told me that the proper way to do string comparisons was basically using the strcmp function, but to my surprise this function doesn't work when I try to run it using Xcode but works fine in Visual Studios, so this got me wondering if this is not a C++ function.
Is strcmp a c++ function?
What would be the correct way to compare two strings?
Can someone be so kind and explain this function a little bit?
A C++ string, which is created using string, like this: string someStringObject;
is a proper grown-up object that has a == operator well-defined and does what you expect.
A C-style string is a pointer to a char, with the unchecked promise that it's an array of char actually, and that you have definitely put a zero value at the end of the letters. Because these are simply char pointers, trying to use the == on them will actually be comparing the values of two pointers, which is not what you care about, so you need a function to use those pointers and check the array of chars they point to. This function is called strcmp. In C++, it lives in <cstring>.
A c-string is an array, which degenerates into a pointer at every opportunity, and even if the things you are comparing have the same text, they will only compare equal if they are in fact the same piece of memory.
The strcmp() function actually traverses the strings to see if the arrays match character by character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
#include <string.h>
int main()
{
constchar one[] = "Hello world!";
constchar two[] = "Hello world!";
if (one == one) puts( "Yeah: &one == &one" );
else puts( "fooey" );
if (one == two) puts( "fooey two" );
else puts( "Yay! &one != &two" );
if (strcmp( one, two ) == 0) puts( "contents of one[] == contents of two[]" );
else puts( "fooey three" );
return 0;
}
Line 16 of the C++ code is basically the same as line 15 of the C code. The trick is that in C++, the std::string class has the operator == () function overloaded to compare two strings character by character.