C++ Expression preceding parentheses - c++

I'm currently working on a set of code where we had to rework the code from all being written in the main and breaking it up into two subfunctions and the main. I've broken it up, but I am having trouble reading in one of my subfunctions. I never learned parameter passing in depth because my professor only briefly touched on it.
The error I'm getting is "Expression preceding parentheses of apparent call must have (pointer-to-) function type."
This is the line of code I'm having an issue with:....
type = selectCarpet(type, unitPrice);
unitPrice = oneRoom(pricePerSqYd, count, ftLength, ftWidth, ftSq, ydSq, squareYd, materialCost, totalCost, unitPrice);
and this is the function:
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <string>
using namespace std;
const double BEST = 6.99,
MEDIUM = 4.59,
BASIC = 3.50,
INSTALL = 129.99;
const int NINE = 9;
int selectCarpet(int type, int unitPrice);
double oneRoom(double pricePerSqYd, int count, double ftLength, double ftWidth, int numRooms, double ftSq, double ydSq, int squareYd, double materialCost, double unitPrice, double totalCost);
int main()
{
double ftLength, // room length in feet
ftWidth, // room width in feet
ftSq, // square footage
ydSq, // square yard
materialCost, // carpet material cost
totalCost, // material cost plus install
grandTotal,
unitPrice;
int squareYd, // square yards, round off
type, // carpet type
count,
numRooms;
type = 0;
unitPrice = 0;
double pricePerSqYd,
oneRoom;
type = selectCarpet(type, unitPrice);
totalCost = 0;
cout << "\nEnter number of rooms: ";
cin >> numRooms;
unitPrice = oneRoom(pricePerSqYd, count, ftLength, ftWidth, ftSq, ydSq, squareYd, materialCost, totalCost, unitPrice);
// step 11
grandTotal = 0;
grandTotal += totalCost;
cout << "\n\nThe grand total price is "
<< grandTotal << endl;
// step 13
do
{
cout << "\n\t\t*** CARPET INSTALLATION ***\n\n";
cout << "Select carpet type:\n"
<< "1 - Best Quality, Unit Price $6.99\n"
<< "2 - Medium Quality, unit price $4.59\n"
<< "3 - Basic Quality, Unit price $3.50\n"
<< "4 - exit\n"
<< "Enter your choice --> ";
cin >> type;
} while (type != 1 && type != 2 && type != 3 && type != 4);
return 0;
}
int selectCarpet(int type, int unitPrice)
{
do
{
cout << "\n\t\t*** CARPET INSTALLATION ***\n\n";
cout << "Select carpet type:\n"
<< "1 - Best Quality, Unit Price $6.99\n"
<< "2 - Medium Quality, unit price $4.59\n"
<< "3 - Basic Quality, Unit price $3.50\n"
<< "4 - exit\n"
<< "Enter your choice --> ";
cin >> type;
} while (type != 1 && type != 2 && type != 3 && type != 4);
while (type != 4)
{
// step 2
if (type == 1) unitPrice = BEST;
else if (type == 2) unitPrice = MEDIUM;
else if (type == 3) unitPrice = BASIC;
}
return unitPrice;
}
double oneRoom(double pricePerSqYd, int count, double ftLength, double ftWidth, int numRooms, double ftSq, double ydSq, int squareYd, double materialCost, double unitPrice, double totalCost)
{
for (count = 0; count < numRooms; count++)
{
cout << "Enter room length in feet: ";
cin >> ftLength;
cout << "Enter room diwth in feet: ";
cin >> ftWidth;
// step 5
ftSq = ftLength * ftWidth;
// step 6
ydSq = ftSq / NINE;
// step 7
squareYd = int(ydSq + .5);
// step 8
materialCost = squareYd * unitPrice;
// step 9
totalCost = materialCost + INSTALL;
// step 10
cout << setiosflags(ios::fixed | ios::showpoint)
<< setprecision(2);
cout << "\n\nSquare footage of the room is: " << ftSq
<< "\nSquare yard of the room is:\t" << ydSq
<< "\nSquare yards priced for: " << squareYd
<< "\nMaterial Cost:\t$" << materialCost
<< "\nInstallation\t$" << INSTALL
<< "\nTotal Cost\t$" << totalCost
<< endl << endl;
}
return pricePerSqYd;
}
any help is appreciated as I have almost no idea what I am doing here. Thank you.

This declaration within main():
double pricePerSqYd,
oneRoom;
shadows the declaration of your function outside of main():
double oneRoom(..., ...);
Name lookup finds the variable first, but you can't call a double. Hence the error. Just rename one or the other.

Related

C++ Program using functions

I'm writing a program for my C++ class I've complete the program. but it won't compile. I'm new to programming so I don't really know what I'm doing wrong. If there is anyone on here that can point me in the right direction. Please help me!
Prompt Description:
Write a C++ program to calculate free estimate for carpet and furniture cleaning of residential and business customers. The program continues until end of file is reached.
Fro residential customers, specify and update number of small couches ($50 each), large couches ($80 each), rooms ($70 each) and steps ($5 each) until exit is selected. the bill is calculated based on the number of items. If the amount is more than 500 dollars, a discount of 10% is applied to the bill. Then the customer is offered to select from an installment of 1,2,3, or 4 or press 0 to exit. Based on an installment option, the bill is increased slightlenter code herey, and each installment amount is calculated.
For business customers, ask the user to enter the amount of square footage and then the bill is calculated at .45 per square foot.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int exit = 0;
int smallcouches = 1;
int largecouches = 2;
int rooms = 3;
int steps = 4;
const float SMALL_COUCH = 50.0;
const float LARGE_COUCH = 80.0;
const float ROOMS = 70.0;
const float STEPS = 5.00;
const float PER_SQUARE_FOOT = 0.45f;
const float DISCOUNT_QUALIFIED = 500.0;
const float DISCOUNT = 0.10f;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
const int FOUR = 4;
const float RATEONE = 0.0f;
const float RATETWO = 0.0535f;
const float RATETHREE = 0.055f;
const float RATEFOUR = 0.0575f;
float billAmount;
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED);
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps);
void InstallmentPlan(float billAmount);
void BusinessEstimate(float PER_SQUARE_FOOT);
int main()
{
cout << fixed << showpoint << setprecision(2);
int customerType, residential_customer, business_customer;
char B, b, R, r;
residential_customer = R || r;
business_customer = B || b;
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; //Enter customer type
cout << endl;
while (cin) //While there is input to read
{
if (customerType == R || customerType == r) //if residential customer
{
ResidentialEstimate(SMALL_COUCH, LARGE_COUCH, ROOMS, STEPS, DISCOUNT_QUALIFIED); // call function ResidentialEstimate
InstallmentPlan(billAmount); // all function Installmentplan
}
else if (customerType == B || customerType == b) //else if business customer
{
BusinessEstimate(PER_SQUARE_FOOT); //call function BusinessEstimate
}
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; // Enter cutomer type
cout << endl;
}
return 0;
}
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED)
{
GetResidentialItems(smallcouches, largecouches, rooms, steps); //Call function GetResidentialItems to get items to clean
billAmount = (SMALL_COUCH + LARGE_COUCH + ROOMS + STEPS); //Calculate the bill amount
if (billAmount > 500) //if bill amount is more than 500 dollars
{
DISCOUNT_QUALIFIED = billAmount * 0.10f;
billAmount = billAmount - DISCOUNT_QUALIFIED; //Apply a discount of 10% to the bill amount
}
return billAmount; //return bill Amount
}
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps)
{
int count;
int choice = smallcouches || largecouches || rooms || steps;
//Ask user to select an item to update or press 0 to exit
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
while (choice > 0) //while user hasn't pressed 0
{
choice = count;
cout << "Please enter the number of " << choice; //ask the user to enter a number from the item selected
cin >> count;
cout << endl;
//Show the current selections and numbers
cout << "Current selections: " << count << " Small Couches, " << count << " Large Couches, " << count << " Rooms, " << count << " Steps.";
//Ask user to select an item to update or press 0 to exit
choice = 0;
count = 0;
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
}
}
void InstallmentPlan(float billAmount)
{
int num;
int installment = 0;
int bill = 0;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
while (num > 0) //while user hasn't pressed 0
{
//calculate the installments
if (num == 1)
installment = billAmount;
else if (num == 2)
{
bill = billAmount * 0.0535f;
installment = bill / num;
}
else if (num == 3)
{
bill = billAmount * 0.055f;
installment = bill / num;
}
else if (num == 4)
{
bill = billAmount * 0.0575f;
installment = bill / num;
}
cout << "With " << num << " installment your bill of " << billAmount << " will be worth " << bill << "." << endl;
cout << "Each installment will be worth " << installment << endl;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
}
}
void BusinessEstimate(float squarefootage)
{
//Ask user for the square footage
cout << " Enter the approximate square footage: ";
cin >> squarefootage;
cout << endl;
//Calculate the bill amount
billAmount = squarefootage * PER_SQUARE_FOOT;
cout << "Your free Business Customer Estimate for " << squarefootage << "square footage = " << billAmount;
}

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;
}

How could I improve this c++ program without vectors?

**Guidelines:**get 3 seperate lists of data(array) for head of household, annual income, and household members, then get all annual incomes and average them together. Display in a neat table.
This is from a school project I wasn't allowed to use anything very advanced but I'd like to go back and improve it now. I'd like ti make it cleaner and particularly like to find more that I can take away from it than add to it.
// <Program Name> Programming Project #3 Average Income (Using Functions and Arrays)
// <Author> Brendan Jackson
// <Date of Programs Release> 08/05/15
// <Program Description> takes 3 arrays and displays them with average income
#include <iostream> // allows cin and cout statements
#include <iomanip> //allows setprecision
#include <string> //allows strings
using namespace std; // Namespace std allows program to use entities from <iostream>
int input(string[], int[], double[]); //function 1
double calculate_average_income(double[], int); //function 2
void display_survey_data(string[], int[], double[],int , double); //function 3
int main() // main function
{
//variables for functions
string name[10];
int members[10];
double income[10];
int count_of_households;
double average;
//get input
count_of_households = input(name, members, income);
//calculate average
average = calculate_average_income(income, count_of_households);
//output all data in table
display_survey_data(name, members, income, count_of_households, average);
return 0;
}
int input(string name[], int members[], double income[]) //function 1
{
// get household info
int count_of_households = 0;
cout << "How many house holds were there? ";
cin >> count_of_households;
//TODO: handle bad input (characters and decimals)
if (count_of_households >= 11 || count_of_households < 0)
{
cout << "must enter valid # " ; //TODO: more description
count_of_households = 0; //set back to safe value
}
else
{
//cycle through arrays
for (int count = 0; count < count_of_households; count++) //TODO: take out (count + 1) start from 1 alternatively
{
// get survey info for names
cout << "Enter household #" << (count + 1) << "'s head of household name\t" ;
cin.ignore() ; // ignores keyboard buffer characters
getline (cin, name[count]) ;
// get survey info for income
cout << "Enter household #" << (count + 1) << "'s annual income\t" ;
cin >> income[count];
// get survey info for members
cout << "Enter household #" << (count + 1) << "'s household members\t" ;
cin >> members[count];
}
}
return count_of_households;
}
double calculate_average_income(double income[], int count_of_households) //function 2
{
//add incomes together
double total = 0.0;
double average = 0.0;
//loop over income
for (int count = 0 ; count < count_of_households; count++)
{
//add income to runnning total
total += income[count];
}
// save calculations
average = total / count_of_households;
return average;
}
void display_survey_data(string name[], int members[], double income[],int count_of_households, double average) //funtion 3
{
//print out header
cout << setw(30) << ""
<< setw(30) << ""
<< setw(30) << "NUMBER OF\n" ;
cout << setw(30) << "HOUSEHOLD NAME"
<< setw(30) << "ANNUAL INCOME"
<< setw(30) << "HOUSEHOLD MEMBERS\n" ;
cout << setw(30) << "--------------------"
<< setw(30) << "---------------"
<< setw(30) << "------------------------\n" ;
///loop over values
for (int count = 0 ; count < count_of_households; count++)
{
cout << setw(30) << name[count]
<< setw(30) << setprecision(2) << fixed << showpoint << income[count]
<< setw(30) << members[count]
<< endl;
}
// display average
cout << endl
<< setw(30) << "AVERAGE INCOME"
<< setw(30) << average
<< endl;
}
You could use std::array
This is simply an array on the stack, just like you used, but has iterators, type safe, bound safe, use value semantics and work with most stl algorithm.
It is declared like this:
array<string, 3> myArray;
And it must be passed by reference, because passing by value will copy it's content:
void doSomething(array<int, 6>& aArray) {
// do something
}
Notice that you must specify the length of the array, since it's a template parameter. If you want to have an array of any size, use tempaltes:
template<size_t length>
void foobar(array<double, length> theArray) {
// do something else
}

C++ Airfare Charge Calculation project

I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100

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.