Introduction
This question is related to the comparison of const char* if() with “SRAD” and whether it returns false. The const char* if() comparison is a type of comparison used in C++ programming language. It is used to compare two strings and determine if they are equal or not. In this case, the comparison is between the const char* if() and the string “SRAD”. This question will discuss the details of this comparison and why it returns false.
Solution
This question is a duplicate and has already been answered.
The answer is that the comparison of a const char* with “SRAD” will return false because the const char* must be a null-terminated string of characters, and “SRAD” is not a null-terminated string.
This compares the pointers, not the contents.
You need to use strcmp
:
if(strcmp("SRAD", name) == 0)
1
solved const char* if() comparison with “SRAD” returns false [duplicate]
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
The comparison of a const char*
with the string literal "SRAD"
will always return false
. This is because a const char*
is a pointer to a character array, while a string literal is a pointer to a constant character array. The two are not the same type, and therefore cannot be compared.
In order to compare a const char*
with a string literal, you must use the strcmp()
function. This function takes two parameters, both of which must be of type const char*
. It will then compare the two strings and return 0
if they are equal, or a non-zero value if they are not.
For example, if you have a const char*
called str
and you want to compare it to the string literal "SRAD"
, you would use the following code:
if (strcmp(str, "SRAD") == 0)
{
// The strings are equal
}
else
{
// The strings are not equal
}
This will compare the two strings and return true
if they are equal, or false
if they are not.