Why won't my if statement work!?

Started by
2 comments, last by Zahlman 14 years, 11 months ago

for (int i = 0; i < word.length(); i++)
{
	if (&word == "<")
        {
		inTag = true;
	} else if (&word == ">")
	{
		inTag = false;
	}
}


Basically I'm feeding it an html document and so when it comes across a tag it should see the "<" symbol and recognize that it's looking at a tag, and when it reaches the end it'll see the ">" symbol and know the tag has been closed, and output the words not in tags into a separate file. I tested everything else and the string "word" is as it should be, and that should be the only factor affecting this.
Advertisement
Assuming that word is a std::string, the main issue is that you're taking the address of a character at position i, and then attempting to compare it to a string. While this may compile, it won't do what you're expecting. Essentially, you're just comparing two random locations in memory to see if they are equal.

To make this correct code, we must make two main modifications.

1: We are not comparing the memory location of the characters, so we need to drop the & operator.

2: We are not comparing a string to another string, we are comparing a character to another character. So, we need to replace "<" and ">" (String literals) with '<' and '>' (Character literals).

[size=1]Visit my website, rawrrawr.com

Wow, thank you so much. I totally forgot about the character literals thing. There's just so much to remember with C++.
Er, there *is* more code inside the for-loop in the actual code, yes? :)

This topic is closed to new replies.

Advertisement