Walker
Walker

Reputation: 3

How to use a counter with a 'do while' loop in C++?

I am trying to get this 'do while' loop to run 3 times and then display the amount in the accumulator contain within a while loop inside the 'do while' loop.

It seems to be counting correctly, but only runs the while loop on the first. When run, instead of going on to ask for the next set of numbers, it just displays the first batch (added up correctly). I have tried switching some of the code around and searching google, but can't find the answer.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int storeNum = 1;
    int payRollAmount = 0;
    int totalPayroll = 0;

    do
    {
        cout << "Store " << storeNum << ":" << endl;

        while (payRollAmount <= -1)
        {
            cout << "Enter Store's Payroll Amount (-1 to exit): ";
            cin >> payRollAmount;

            totalPayroll += payRollAmount;
        }

        storeNum++;
    } while (storeNum <= 3);

    cout << "The Total Payroll is: " << totalPayroll << endl;

    system("pause");
    return 0;
}

The code should take in an unknown amount of "payrolls," allow you to exit using -1, and then continue on to the next stores payrolls. It should do this 3 times, and then display the total amount (all numbers entered added together.

Upvotes: 0

Views: 92

Answers (1)

jspcal
jspcal

Reputation: 51914

Hi perhaps reset payRollAmount at each iteration? That way it will continue to request the input.

for (int amount = 0; amount != -1; ) {
    cout << "Enter Store's Payroll Amount (-1 to exit): ";
    cin >> amount;
    totalPayroll += amount;
}

Upvotes: 1

Related Questions