Need idea for a while condition

Bascially, I have a string called 'fileContent' that contains the text of a file that has been read and I just need the while loop to loop until I've searched through the entire string but i'm struggling to come up with a suitable condition. Has anyone got an idea?
1
2
3
4
5
6
7
8
9
while(true) { // true is being used in the mean time for debugging purposes
		if(rightBracket!=std::string::npos) {
			leftBracket = fileContent.find_first_of('<',rightBracket);
			rightBracket = fileContent.find_first_of('>',leftBracket)+1;
			
			stackElement = createSubString(ptr_fileContent, leftBracket, rightBracket); // get tag to put in stack
			myStack.push(stackElement);
			std::cout << myStack.top() << "\n";
		}


Anything i've tried at the moment is leaving me with an "Unhandled exception at 0x7702e124 in HTML_Analyzer.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0037f630.."
pushing onto your stack could kill your iterators (I think), meaning that the next time you come around the while loop, rightBracket could be invalid (it may or may not be std::string::npos though).
Last edited on
Could you explain what you mean a bit further? Up until when it goes a bit tits up, the rightBracket variable is performing as it should as you can tell from what the stack is outputting i.e each string on the stack is finishing with a '>'.

(If it helps to know, the program i'm writing is a program that takes in html code, breaks up individual tags and puts them on a stack - as a basic overview anywho... hence the 'leftBracket' and 'rightBracket' vairables. Although I think you already know about this.)
firedraco: std::string::find_first_of() doesn't return an iterator. Check the reference.

mcleano: Am I correct in assuming createSubString() does exactly the same as std::string::substr(), only without bounds checking? My guess is that line 3 is assigning std::string::npos to leftBracket and createSubString() is going over the end of ptr_fileContent.
Er, whoops. Epic fail there >_>

I think helios got it right.
Helios: Yes thats correct:

1
2
3
4
5
6
7
8
std::string createSubString(std::string *ptr, size_t left, size_t right)
{
	std::string stackElement;

	stackElement = ptr->substr(left, right-left);
	
	return stackElement;
}


And yes your guess was right! After adding a check after 'leftBracket's assignment to see if it was equal to std::string::npos it returns true. This is what I now have:

1
2
3
4
5
6
7
8
9
10
11
while(true) {
		leftBracket = fileContent.find_first_of('<',rightBracket);
		if(leftBracket==std::string::npos)
			break;
		rightBracket = fileContent.find_first_of('>',leftBracket)+1;
		
		
		stackElement = createSubString(ptr_fileContent, leftBracket, rightBracket); // get tag to put in stack
		myStack.push(stackElement);
		std::cout << myStack.top() << "\n";	
	}
Topic archived. No new replies allowed.