zachstarnes zachstarnes - 2 months ago 6
C++ Question

While loop exits after one iteration

I am making a hanoi game for a class assignment and I have gotten it all done except the fact that my main while loop exits after the first iteration and I can not figure out why. If there is any way someone could look at the while loop and help me figure out why that would be great!

Here is the main function with the while loop. I can get both inputs and after I press enter after entering the destination tower it exits.

void Hanoi::start()
{
int startPos = -1;
int endPos;
int beingMoved;

// Populate the first peg with the number of rings needed
for(int i = m_numDisks; i > 0; i--)
tower[0].push_back(i);

display();

while(startPos != 0)
{
// Get the starting tower the user wants
std::cout << "\n";
std::cout << "Select starting tower (Enter 0 to end): ";
std::cin >> startPos;

if(startPos == 0)
break;

// Get the destination tower the user wants to move the disk to
std::cout << "Select destination tower (Enter 0 to end): ";
std::cin >> endPos;

if(endPos == 0)
break;

// Shift the start and end position to account for 0 index
startPos = startPos - 1;
endPos = endPos - 1;

// Use the startPos and endPos to move the last element in the vector to the desired tower
if(!tower[startPos].empty())
{
beingMoved = tower[startPos][tower[startPos].size() - 1];

if(endPos != startPos || tower[endPos][tower[endPos].size() - 1] > beingMoved)
{
tower[endPos].push_back(beingMoved);
tower[startPos].pop_back();
}
else
{
std::cout << "The starting tower and the ending tower must be different and the disk you are moving must be smaller than the disk at the destination. Please try again.";
}
}

// Display the towers and their disks
display();
}
}

Answer

I would use a different variable for this:

// Shift the start and end position to account for 0 index
startPos = startPos - 1;

Are you typing one as the starting position? if so then startpos = 0 after this statement and then it exits in the while condition.