C++ - Comparing Strings Function not working?
I am currently writing an HTML toke开发者_如何学Gon recognizer in c++. I am using stacks to check and see if there are beginning and matching tags.
Before I can match my tags I need to make sure that the tag is valid. But for some reason my checking function is not working. I step through each step in the algorithm and from everything i see this should work. Yet it is returning false every time. Here is my code:
const int NUM_TAGS = 12;
char *tagNames[NUM_TAGS] =
{
"<html>",
"</html>",
"<head>",
"</head>",
"<title>",
"</title>",
"<body>",
"</body>",
"<p>",
"</p>",
"</>",
"<SPOT/>",
};
bool check_ValidTag(char check[])
{
for (int i=0; i<=NUM_TAGS; i++)
{
if (check==tagNames[i])
return true;
}
return false;
};
I am calling the function like this:
tok.isValid = check_ValidTag((char*)tok.str);
As Requested Here is what the struct "tok" looks like..
struct token
{
char name[MAX_NAME + 1];
int type;
bool isValid;
char str[MAX_LENGTH + 1];
};
Any Ideas? Thanks.
You're comparing pointers, not the strings' contents. Replace
char *tagNames[NUM_TAGS] =
with
std::string tagNames[NUM_TAGS] =
The ==
operator on char *
doesn't compare the contents of the strings. It compares the addresses of the strings. If you are working with C-style strings you should use strcmp
to compare them.
However since this is tagged as C++ I would recommend that you use std::string
instead of char *
.
As other people pointed out, you are comparing a pointer to char array (not the actual string content). If you can change the implementation to use std::string, the "==" overloaded operator should do the trick for you.
However, if you need to stick with the char array. Do it c-style:
{
if(strcmp(check, tagNames[i])==0)
}
Or if you like to stay c-plus-plussy, you could use the compare()
function from char_traits<char>
.
typedef std::char_traits<char> ct;
bool check_ValidTag(char check[])
{
size_t check_len = ct::length(check);
for (int i=0; i<=NUM_TAGS; i++)
{
if( 0 == ct::compare(check, tagNames[i], check_len) )
return true;
}
return false;
};
See the documentation at www.cplusplus.com.
精彩评论