You cannot compare the contents of strings (or any other array type) with the standard relational operators like ==
, <
, >
, etc. You will need to use the strcmp
library function instead:
#include <string.h>
...
if (strcmp(TextA, word) == 0)
{
// strings are equal
}
strcmp
will return an integer value < 0 if TextA
is lexicographically less than word
, 0 if they are lexicographically equal, and > 0 if TextA
is lexicographically greater than word
.
Note that, in the C locale, this means strings will be ordered "ASCIIbetically"; that is, any string beginning with 'a'
will come after a string beginning with 'Z'
, since the ASCII code for 'a'
is greater than 'Z'
.
So why can't you use ==
for comparing strings?
Except when it is the operand of the sizeof
, _Alignof
, or unary &
operators, or is a string literal being used to initialize an array in a declaration, an expression of type "N-element array of T
" will be converted to an expression of type "pointer to T
", and its value will be the address of the first element of the array.
This means that, in the condition TextA == word
, both of the expressions TextA
and word
are being converted to pointer values; instead of comparing the contents of the two arrays, we're comparing their addresses.