First of all, thank you for reading this. This code is for a project in my college class. For every scenario this program works just fine. The only issue I am having is when the user enters a value that is 0 or negative. The program is supposed to just print "The number of units must be 1 or more" and exit the program in the while loop for the getQuantity function, but for some reason it also prints "The total sale for the customer is $0.00" which is in the displaySale function. Any help with this would be greatly appreciated. I just can't figure out where the issue is coming from.
I did not test however I think the error lies in getQuantity() function in specific the loop\while. I would recommend you change the function into:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int getQuantity()
{
int quantity;
cout << "Enter the number of units sold: ";
cin >> quantity;
if(quantity < 1) // If user inputs anything smaller than 1.
{
cout << "The number of units must be 1 or more\n";
return 0;
}
return quantity;
}
Another option would be to #include <cstdlib> and change your getQuantity function to
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
int getQuantity()
{
int quantity;
cout << "Enter the number of units sold: ";
cin >> quantity;
if (quantity <= 0)
{
cout << "The number of units must be 1 or more\n";
exit(0); // <-- Here
}
return quantity;
}
Thank you so much! I added the if statement in the main function and now it works just fine. You saved my sanity. I'm still not 100% sure why I would need two return 0; calls, but I'll dig around in my book and figure it all out. Thanks again.
The return 0; in getQuantity doesn't exit the program.
It simply returns 0 to the function that called it -- namely, the main function, where it gets stored into the quantity variable.