I've been having trouble with a project I've been working on. The program is supposed to allow the user to enter an unknown number of payroll amounts for three stores: Store 1, store 2, and store 3. The program should calculate the total payroll and then display the result on the screen. Here's the code:
#include <iostream>
using namespace std;
int main()
{
int userAmount = 0;
int totalPayroll = 0;
for (int x = 1; x <= 3; x ++)
{
while (userAmount >= 0)
{
totalPayroll += userAmount;
cout << "Enter payroll amount for store (-1 to stop): " << x << " :" << endl;
cin >> userAmount;
cout << "Total payroll for store " << x << " :" << totalPayroll << endl;
When started, it is supposed to take as many amounts as the user wants, and add them to a total payroll. Then they move to the next store, then the next, each time inputting as many amounts as they need and showing the total payroll for each store.
The problem is that when the first amount is entered for the first store, it is not added to the total payroll, but the second and so on are. The program also doesn't move onto the next store once -1 is entered.
The reason why the first one isn't added is because the addition is being performed before you get their input. So, the first time through, it's adding 0. Then when you input for the second time, it's adding what you first put in, and so on. So move the addition to after the cin.
The reason why it doesn't move on to the next store is because to exit the first store userAmount gets set to -1 and so it tests false in the while loop and the while loop ends. However, afterwards, userAmount never changes from -1, so when the for loop restarts, it tests the while loop again but it still comes up false because userAmount is still -1.
The best fix for this would be to use a do-while loop instead of a while loop.
1 2 3 4 5 6 7 8 9 10 11
// Simply change from this:
while (userAmount >= 0)
{
...
}
// To this:
do
{
...
} while (userAmount >= 0)
A while loop tests the condition before it runs. The do while loop tests the condition at the end, so it always runs at least once. This gives you the opportunity to change the value of userAmount.