Have you tried using your debugger to check variable values and such during your program's execution?

Perhaps this will give you some insight as to why it doesn't work all the time.

Furthermore, when you say "it doesn't work sometimes", what exactly does that mean? What errors are you getting, or what is happening to make you think that?

These are things we need to know which you have left out.

More or less, when programs have somewhat complicated logic like this, it is very hard, if not impossible, for us to tell exactly where the problems lies.

Dust off your debugger, or use come cout statements in your code, and try to at least narrow the problem down to specific piece of code.

Then come back, and we can help you