Infinite Do / While loop, help!

I'm working a parsing program that generates random c++ code. I have a class called Production and once there is a non terminal found in the main string I use this loop to compare it the the possibilities I have saved in a vector. The nested If statement works fine and I can see that it returns the right arguments and sets the bool value to true but then is just passes the conditional without breaking. So then I added the || and the second statement so it would at least stop when it gets to the end of the vector but again to luck. What am I missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector<Production>::size_type sz = prodOptions.size();

unsigned int i = 0; bool f = false;
do
{
	cout << "We are here!" << endl; //test
	if (nonTerm == prodOptions[i].getlhs())
	{
	        cout << "Found it" << endl; //test
	        strReplace = prodOptions[i].expand();
	        f = true;
	}
	else
		i++;
} while (f != true ||  i < sz);
Hi,

try using a debugger, see what the values of the variables are hence deduce where things go wrong.

Btw

} while (f != true || i < sz);

can be written:

} while (!f || i < sz);

This is another example of why I don't like do loops; Why can't you have :

1
2
3
4
while (!f) {
// ...
// ....
}


Also f is a terrible variable name.
Also, you could just use the find_if algorithm, with your own predicate function:

http://www.cplusplus.com/reference/algorithm/find_if/
Last edited on
You might start by using the right operator:
while (f != true && i < sz)
Last edited on
Thanks for the help everyone, I ended up using a break statement after the If statement and it works perfect now. BTW mbozzi, there is a reason this post was in the beginner forum, thanks for your input though.
Topic archived. No new replies allowed.