Loop accepts first set of input and then reuses that value - c++

I am currently learning C++ in school and one of our projects is to create a program to calculate a budget. When I run my program, the loop that accepts the input for item cost will take the input once and then reuse that value each time it loops back. I have already searched online for a solution and my teacher is just as confused about it as I am. It could be that there is a problem with Codeblocks but I have already tried it with a different editor. If anyone knows how I can fix it, that would be great.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
bool taxable = true;
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use either true or false): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == true){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}

As said in the comment, you can't use cin on boolean. From the doc :
The standard input stream is a source of characters determined by the environment.
So here's your fixed code (which will accept Y and nothing else) :
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
char taxable = '';
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use Y for Yes): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == 'Y'){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}

Related

Passing information obtained from a cin command to an argument in a while loop (C++)

I'm having trouble passing the reentered optionPackageCode after the nested while loop completes (cin >> optionPackageCode;) back to the first while loop so that it can check the conditions with the updated code. No clue what's wrong.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Declaring variables
double basePrice = 0.0;
double subTotal = 0.0;
double associatedCosts = 0.0;
double finalPrice = 0.0;
int sub = 0;
int tries = 0;
string optionPackageCode = "";
//Populating arrays
string optionPackageCodeArray[5] = { "BB", "SP", "NP", "HE", "UC"};
string packageNameArray[5] = { "Base", "Sport", "Intermediate", "Luxury", "Custom"};
double packageCostArray[5] = { 1500.00,3250.00,4575.00,7500.00,5220.00 };
//Ask for input
cout << "Welcome! Please enter the base price and option package code for your vehicle!"
<< endl;
cout << fixed << setprecision(2);
cout << "Base Price: ";
cin >> basePrice;
cout << endl << "Option package code: ";
cin >> optionPackageCode;
//While loop
while (tries < 5 && optionPackageCodeArray[sub] != optionPackageCode)
{
tries += 1;
while (optionPackageCodeArray[sub] != optionPackageCode && sub < 5)
sub += 1;
//end while
cout << "Sorry, that code wasn't found in our database! Please try again: " << endl;
cin >> optionPackageCode;
} //end while
//Calculations and final output
if (optionPackageCodeArray[sub] == optionPackageCode)
{
subTotal = basePrice + packageCostArray[sub];
associatedCosts = subTotal * 0.15;
finalPrice = subTotal + associatedCosts;
cout << "The final cost for your vehicle with " << packageNameArray[sub] << " trim is $" << finalPrice << endl;
}
else
cout << "Sorry, you are out of tries...";
system("pause");
return 0;
}

why is my code not accepting letters as user input

my code runs without errors or anything but after I put in an "F" or "P" it skips to "click any button to continue" but if I use any numbers it goes through the code fine.
Here is my code:
#include <iostream>
#include <iomanip> // needed to use set precision
using namespace std;
void calcCost(double f_benefits, double F, double total_cost, double emp_salary)
{
if (f_benefits == F)
(total_cost += emp_salary * 1.5);
else
(total_cost += emp_salary * 1.25); // calculating operating function
}
int main()
{
double num_emp = 0; // employees
double emp_salary = 0; // employees salary
double f_benefits = 0; // are they full time or part time benifits
double total_cost = 0;
int F = 0;
int P = 0;
cout << setw(69) << "Cost of Operation\n\n";
cout << "Please enter the number of employees to process: ";
cin >> num_emp;
cout << endl;
for (int i = 1; i <= num_emp; i++) // loop for each employees salary and benifits
{
cout << "Please enter the salary for employee " << i << ":";
cin >> emp_salary;
cout << "Is employee " << i << " receiving(F)ull or (P)artial benefits ? Please enter F or P : "; // Dont forget input validation for this step
cin >> f_benefits;
}
return 0;
}
Shouldn't f_benefits be a string?
The "cin >> f_benefits" is trying to read a double value. You should read the response into a char or string. Reading into a string expects a newline before returning.
You should also check that you got an "F" or "P" .

When using vector and arrary for multiple customer data it does not calculate correctly

When I run the program with either one or more customers. It seems to be that Only with the first customer data, the code I have does not do the calculations correctly for the first customer when trying to get the monthly payments and interest but the calculations are done correctly for the rest of the customers data inputted. What am I missing? Thank you.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
//Variables
vector <double> Loanlgth, Loanamt, interestRate;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100), totalInterest;
char yes;
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
vector <string> customerName;
int option;
int numCustomers = 0;
int index = 0;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1) //Customer enters their information
{
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate, tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
}
}
if (option == 2) // Displays monthly payment
{
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
cout << customerName[index] << " your total loan is " << loanTotal[index] << "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
} while (option != EXIT_PROGRAM);
system("pause");
return 0;
}
Currently, interestRate is populated wrongly. Initially, it contains a garbage value because it is not initialized and if the first condition is not true, the garbage value is pushed, otherwise .12. Next, if the second condition is true, .05 is pushed, otherwise the values from the above flow. So, these combinations of garbage and assigned values are causing values to be pushed twice.
Here's your code:
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
You can correct this in a number of ways:
// push after the calculation is complete
if (tempcreditScore <= 600)
tempinterestRate = .12;
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with if-else (preferable):
if (tempcreditScore <= 600)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with ternary operator ?: (conciseness and you can make it const):
const double tempinterestRate = (tempcreditScore <= 600 ? .12 : .05);
interestRate.push_back(tempinterestRate);
Apart from this, there are a number of points:
The naming convention is inconsistent throughout the code.
The variables must be initialized because the uninitialized ones may lead to Undefined Behavior.
In the absence of an aggregate type such as struct or class and with multiple pieces of information to store separately in vectors, it is better to keep all the push_backs exactly to once per iteration.
Magic numbers can be avoided for 600, .12 and .5.
The magic numbers for option comparison in if conditions can be removed with their proper constant equivalents i.e. INPUT_CUSTOMER and DISPLAY_LOAN. And, if-else can be used instead of if-if.
The scoping could be improved by moving the variables and objects closer to where they are used.
The vertical blank spaces can improve readability for relevant code blocks.
And, Why is "using namespace std;" considered bad practice?
There might be some other points that you can observe in the following updated code (live):
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
int main()
{
// Variables
std::vector<std::string> customerNames;
std::vector<double> loanLengths, loanAmounts, interestRates;
std::vector<double> monthlyPays, loanTotals, creditScores, totalInterests;
// Program
std::cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option = EXIT_PROGRAM;
do
{
std::cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
std::cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
std::cout << "Please enter a valid menu option: ";
std::cin >> option;
}
if (option == INPUT_CUSTOMER) //Customer enters their information
{
int numCustomers = 0;
std::cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
std::cin >> numCustomers;
for ( int index = 0; index < numCustomers; index++ )
{
std::string name;
double loanAmount = 0.0, loanLength = 0.0, creditScore = 0.0;
std::cout << "Please enter your name: ";
std::cin >> name;
customerNames.push_back( name );
std::cout << "Please enter the loan amount: $";
std::cin >> loanAmount;
loanAmounts.push_back( loanAmount );
std::cout << "Please enter the length of the loan in months: ";
std::cin >> loanLength;
loanLengths.push_back( loanLength );
std::cout << "What is your current credit score? ";
std::cin >> creditScore;
creditScores.push_back( creditScore );
double interestRate = 0.0;
if (creditScore <= 600)
interestRate = .12;
else
interestRate = .05;
// Ternary operator (?:) may also be used here
// const double interestRate = creditScore <= 600 ? .12 : .05;
interestRates.push_back(interestRate);
//Calculations
const double tempTotalInterest = loanAmounts[index] * interestRates[index];
totalInterests.push_back( tempTotalInterest );
const double tempTotalLoan = loanAmounts[index] + totalInterests[index];
loanTotals.push_back( tempTotalLoan );
const double tempMonthlyPay = loanTotals[index] / loanLengths[index];
monthlyPays.push_back( tempMonthlyPay );
}
}
else if (option == DISPLAY_LOAN) // Displays monthly payment
{
std::cout << std::fixed << std::setprecision(2);
for (int index = 0; index < customerNames.size(); index++)
{
std::cout << "\n---\n";
std::cout << customerNames[index] << " your total loan is " << loanTotals[index]
<< "\nwith a monthly payment of $" << monthlyPays[index]
<< "\nfor " << loanLengths[index] << " months with an interest"
<< "\nrate of " << interestRates[index] << std::endl;
std::cout << "---\n";
}
}
} while (option != EXIT_PROGRAM);
return 0;
}

Nested loops in C++ and user input

Pretty new here to programming, and I have an assignment where I need to achieve the following:
ask for total amount of people
get each of their names
allow user to enter up to 5 scores for each person
if there are less than 5 scores for a given person, inputting -100 will stop it
So far I have written this:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
After getting their name, only the last cout inside the while loop seems to execute first, then it starts from the top and so on until the for loop hits the end depending on totalPerson. I know I'm missing a few things in here, probably in the order of operations and also the way I am executing my loops, but I just can't see it. Could any of you guys with experience in the language please give me any pointers as to what's happening here and how I can fix it? Thank you.
Inside your while group, you only want to use your cout line once (at the beginning looks good).
Your first check should be for ==-100 or similar, since as it is now, you'll get a "Input only scores from 0 to 100" message if you enter -100.
You should keep a cin.ignore(); call after each use of cin >> VARIABLE, since then you will drop the EoL character.
Example code:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
Some of your variables also needed to move inside the for loop.
Additionally I changed the limits on the personScoreCounter to [0:4] rather than [1:5] - this way you can use it for averaging more easily.
You might also try cin.getline() instead of getline(std::cin , ... ):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
This allows whitespaces in the input also.
http://www.cplusplus.com/reference/istream/istream/getline/

C++ Calculation Problem, Always returns $0

I have to display and loop a menu, allowing the customer to make multiple orders for peanuts, movies, or books. The menu displays fine, but the quantity doesn't go down to the calculations part of my code. Everytime I enter a quantity for anything and checkout it returns $0. I have no idea why this is happening I don't see anything wrong with my code, but obviously there is. Do you guys have any suggestions on what to do based on looking at what I have?
#include <iostream>
#include <cstdlib>
using namespace std;
//function declarations
void displayMenu();
//constant statements
const double BOOK_PRICE = 9.00; //price per book
const double BOOK_SHIPPING = 1.06; //shipping per book
const double MOVIE_PRICE = 13.99; //price per movie
const double MOVIE_SHIPPING = .05; //shipping per movie subtotal
const double PEANUT_PRICE = 1.80; //price of peanuts per pound
const double SHIPPING_PRICE = .50; //shipping of peanuts per lb
int main()
{
//declaration statements
int numBooks = 0; //# of books purchased
int numMovies = 0; //# of movies purchased
double numPeanuts = 0.0; //# of peanuts per pound
double bookSubtotal = 0.0; //subtotal of books
double movieSubtotal = 0.0; //subtotal of movies
double peanutSubtotal = 0.0; //subtotal of peanuts
int totalBooks = 0; //running total of books
int totalMovies = 0; //running total of movies
double totalPeanuts = 0.0; //running total of peanuts
int userChoice = 0; //user input
double totalPrice = 0.0; //final price
while (userChoice != 4)
{
displayMenu();
cout << "Enter a menu choice: ";
cin >> userChoice;
if (userChoice == 1)
{
cout << "Please enter the number of books: ";
cin >> numBooks;
totalBooks = totalBooks + numBooks;
}
else if (userChoice == 2)
{
cout << "Please enter the number of movies: ";
cin >> numMovies;
totalMovies = totalMovies + numMovies;
}
else if (userChoice == 3)
{
cout << "Please enter the pounds of peanuts as a decimal: ";
cin >> numPeanuts;
totalPeanuts = totalPeanuts + numPeanuts;
}
else if (userChoice == 4)
{
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
//computations
bookSubtotal = (totalBooks * BOOK_PRICE) + (totalBooks * BOOK_SHIPPING);
movieSubtotal = (totalMovies * MOVIE_PRICE * .05) + (totalMovies * MOVIE_PRICE);
peanutSubtotal = (PEANUT_PRICE * totalPeanuts) + (totalPeanuts * .5);
totalPrice = bookSubtotal + movieSubtotal + peanutSubtotal;
cout << "The total price is $" << totalPrice << endl;
system("PAUSE");
return 0;
}//end of main
void displayMenu()
{
cout << "1 Books" << endl;
cout << "2 Movies" << endl;
cout << "3 Peanuts" << endl;
cout << "4 Checkout" << endl;
}//end of displayMenu
The problem is in the cin >> - you found the answer yourself when you say that the book count is zero. I suggest you try to put << endl after each cout << .... Other solution is to use _flushall(); after each cout.