I have two variables:
char charTime[] = \"TIME\";
char buf[] = \"SOMETHINGELSE\";
I want to check if these two are equal... using ch
You are checking the identity charTime
and buf
. To check the equality, loop over each character in one array and compare them with the related character in the other array.
Check them in a for loop. Get the ASCII numbers for each char once they change they're not equal.
In an expression using ==
the names of char
arrays decay into char*
pointing to the start of their respective arrays. The comparison is then perform in terms of the values of the pointers themselves and not the actual contents of the arrays.
==
will only return true for two pointers pointing to the same location and false otherwise, even if they are pointing to two arrays with identical contents.
What you need is the standard library function strcmp
. This expression evaluates as true if the arrays contain the same contents (up to the terminating null character which must be present in both arrays fro strcmp
to work safely).
strcmp(charTime, buf) == 0
In c you could use the strcmp function from string.h, it returns 0 if they are equal
#include <string.h>
if( !strcmp( charTime, buf ))
char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";
C++ and C (remove std::
for C):
bool equal = (std::strcmp(charTime, buf) == 0);
But the true C++ way:
std::string charTime = "TIME", buf = "SOMETHINGELSE";
bool equal = (charTime == buf);
Using ==
does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.