If statement inside loop not reading total right cout displaying wrong - c++

Hello all I want to do is for last cout statement display whatever apartment has the highest rent and the apartment name. Right now it displays the total rent of all complexes enter and whatever the last complex name entered. I am stuck on this and could really use some help on this. I am new to c++ so please talk to me in layman terms it is hard for me to understand somethings.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("rentfile.txt");
int numComplex, numMonths;
double rent, totalAllRent = 0; //// Accumulator for total scores
string nameComplex;
string highNameComplex;
double averageRent;
double highestRentTotal = 0;
//set up numeric output programing
cout << fixed << showpoint << setprecision(1);
cout << "How many complexes will you enter?";
cin >> numComplex; //number of complexes enter
cout << "How many months of rent will you enter complex?";
cin >> numMonths; //number of months of rent enter
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
outputFile << rent << endl; //write data to output file
totalAllRent = totalAllRent + rent;
if (totalAllRent > highestRentTotal)
{
highNameComplex = nameComplex;
highestRentTotal = totalAllRent;
}
averageRent = totalAllRent / numComplex;
}
}
outputFile.close(); //close the file
ifstream inputFile;
inputFile.open("rentfile.txt");
cout << "Complex Monthly rent Collected per Complex " << endl;
while (inputFile >> nameComplex)
{
for (int i = 0; i < numMonths; i++)
{
inputFile >> rent;
cout << nameComplex << " " << rent << endl;
if (rent == 0)
cout << "Warning one of the complexes submitted zero rent for one of the months " << endl;
}
}
cout << "Total rent collected for the company = " << totalAllRent << endl;
cout << " Average Monthly rent collected for the company = " << averageRent << endl;
cout << highNameComplex << "collect the most rent = " << highestRentTotal << endl;
system("pause");
return 0;
}

Well...if it's me, I'll design the program as follows:
1. Define a vector<vector<double>> vvRents for storing the rents of all apartments by month.
2. Each element in vvRents stores the rents of all months of each apartment.
3. Once all data is collected, calculate summed rents of the year by apartment, and store the total rents in a new vector vTotalRents.
4. Use a max_element algorithm to pick the most expensive apartment.
You must include <vector> to use vector class, and include <algorithm> to use max_element.

Related

Error prompt when attempting to input a char into an int variable [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
How Can I avoid char input for an int variable?
(4 answers)
Closed 5 months ago.
I am trying to make an employee discount program that reads employee number and discount from an input file. I need it to display an error message when a character is put into the variable. I can't seem to figure this out. I'm a newbie so I don't know that many identifiers yet. This compiles with an unexpected output. I'm not sure how to get the variables for all three employees as well. Any help is greatly appreciated.
/* Program name: main.cpp
* Author: Carl Snyder
* Date last updated: 09/11/2022
* Purpose: Top employee discount calculator
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
int winning_Num;
int employee_Num;
double total_Bill;
double discount_Percent;
double discount_Amount;
double bill_After_Discount;
inFile.open("EOM.txt");
inFile >> winning_Num >> discount_Percent;
cout << "Enter your employee number to see if you get a discount: ";
cin >> employee_Num;
cout << fixed << showpoint << setprecision(2);
if (employee_Num >= 10000 && employee_Num <= 99999)
{
if (employee_Num == winning_Num)
{
cout << "You have won a discount of " << discount_Percent << "%." << endl;
cout << "Enter the total bill: " << endl;
cin >> total_Bill;
if (total_Bill > 0)
{
discount_Amount = total_Bill * discount_Percent;
bill_After_Discount = total_Bill - discount_Amount;
cout << "Your discount will take $" << discount_Amount << " off your bill. "
<< endl;
cout << "Your new total is $" << bill_After_Discount << "." << endl;
return 0;
}
if (total_Bill <= 0)
{
cout << "The total should be greater than 0. The program will now
exit.";
}
else
cout << "You entered something that is not a number! The program will
now exit.";
}
else
cout << "Sorry you did not win a discount this month. Try again next
month.";
}
if (employee_Num <=9999 || employee_Num >=100000)
{
cout << "You entered a number that is out of range! Employee numbers are 5
digits (between 10000 and 99999). Program will now exit.";
}
else
cout << "You did not enter a number! The program will now exit.";
return 0;
}

Program cannot run due to no operator "<<" matches these operands

I get an error of "no operator matches these operands" when using the part of the code outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;. Overall, I need the code to Add the ability to save data to disk in one or more files and a menu should give the user the option to save or retrieve data. I have not gotten past the error to properly run the program. Can you please help fix error.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
#include<fstream>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "CourseProjectAvilaF.txt";
//Variables
vector <double> Loanlgth, Loanamt, interestRate, totalInterest;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100);
vector <string> customerName;
int main()
{
menu();
return 0;
}
void menu(void)
{
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option;
//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)
{
writeData();
}
if (option == 2)
{
readData();
}
} while (option != EXIT_PROGRAM);
}
//function to read customer information
void writeData(void)
{
fstream outputFile;
outputFile.open(FileName, fstream::app);
int index;
int numCustomers = 0;
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);
//This will determine interest rate and overall loan amount when calculated
if (tempcreditScore <= 650)
tempinterestRate = .12;
else
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];
// Out put files to write data to be saved
outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;
outputFile << "Your total interest is " << totalInterest << endl;
outputFile << "You owe " << loanTotal << endl;
outputFile << "You have " << Loanlgth << " months to pay off your balance" << endl;
}
outputFile.close(); //Close file
}
//function loan information
void readData(void)
{
int index;
int numCustomers = 0;
ifstream inputFile;
inputFile.open(FileName, fstream::in);//Open the file with read mode
//Display 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;
}
}
It's simple enough, you got it right everywhere else in your program.
When you want to access a particular element of a vector you use an index. Like this
outputFile << customerName[index] << "your Monthly payments are " << monthlyPay[index] << endl;
outputFile << "Your total interest is " << totalInterest[index] << endl;
outputFile << "You owe " << loanTotal[index] << endl;
outputFile << "You have " << Loanlgth[index] << " months to pay off your balance" << endl;
customerName and monthlyPay are vectors. You can't stream them directly. Instead you can do something like
for (auto const &name : customerName)
outputFile << name;

How can I do this without arrays or vectors only using loops

I am almost done with this project just stuck on this last part. Really need help I've reach out to teacher not getting a response. I want to display which complex enter has the highest rent total. Right now I have a double named currentRentAmount which keeps a running total after each loop it reset. So the issue is if the first complex enter was the highest rent collected complex enter it loses that value because its reset to 0. I feel so close yet so far a way. I cant use vector/ array because we technically haven't learn it yet.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("rentfile.txt");
int numComplex, numMonths;
double rent, totalAllRent = 0; //// Accumulator for total scores
string nameComplex;
string highNameComplex;
double averageRent;
double highestComplexRent = 0;
double currentRentAmount = 0;
double previousRentAmount = 0;
//set up numeric output programing
cout << fixed << showpoint << setprecision(1);
cout << "How many complexes will you enter?";
cin >> numComplex; //number of complexes enter
cout << "How many months of rent will you enter complex?";
cin >> numMonths; //number of months of rent enter
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
totalAllRent = totalAllRent + rent;
averageRent = totalAllRent / numComplex;
outputFile << rent << endl; //write data to output file
currentRentAmount = currentRentAmount + rent;
cout << currentRentAmount << endl;
if (currentRentAmount > highestComplexRent)
{
currentRentAmount = highestComplexRent;
}
}
currentRentAmount = 0;
}
outputFile.close(); //close the file
ifstream inputFile;
inputFile.open("rentfile.txt");
cout << "Complex Monthly rent Collected per Complex " << endl;
while (inputFile >> nameComplex)
{
for (int i = 0; i < numMonths; i++)
{
inputFile >> rent;
cout << nameComplex << " " << rent << endl;
if (rent == 0)
cout << "Warning one of the complexes submitted zero rent for one of the months " << endl;
}
}
cout << "Total rent collected for the company = " << totalAllRent << endl;
cout << " Average Monthly rent collected for the company = " << averageRent << endl;
cout << highNameComplex << "collect the most rent = " << highestComplexRent << endl;
system("pause");
return 0;
}
First a friendly note; 'Complex number' means something very specific , you are talking about apartment complex numbers. However, when most people read complex number they think x+iy (think imaginary numbers)
Second , the problem you have is one of logic. You want to find the apt complex with the highest rent, but you seem to update the highest rent value in this condition.
if (currentRentAmount > previousRentAmount)
{
highestComplexRent = currentRentAmount;
}
Ask yourself why you are doing this , what happens in every iteration of the loop. IF currentRentAmount > previousRentAmount since previousRentAmount is always 0.Effectively, this means, if the value of current rent is greater than 0 highest rent is set to current rent.
What you want here is:
1. Make sure highestRentAmount is set to 0 outside of the loops.
2. The if check should be if(currentRentAmount > highestComplexRent) (think through why this will work, I can tell you the answer, but just think about it for a second, its much better to arrive at it yourself)
Good luck
You can use a variable maxComplexRent to keep the track of complexRent.
double maxComplexRent = 0.0;
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
totalAllRent = totalAllRent + rent;
averageRent = totalAllRent / numComplex;
outputFile << rent << endl; //write data to output file
currentRentAmount = currentRentAmount + rent;
cout << currentRentAmount << endl;
}
//Here
maxComplexRent = maxComplexRent>currentRentAmount? maxComplexRent:currentRentAmount;
currentRentAmount = 0;
}
Few suggestions here:
It does not use the correct variable:
if (currentRentAmount > previousRentAmount)
should be changed to
if (currentRentAmount > highestComplexRent)
This line should be moved out to the outer loop (although it is unused):
averageRent = totalAllRent / numComplex;
Remove the unused variables.
if statement was wrong able to fix
if (currentRentAmount > highestComplexRent)
{
highestComplexRent = currentRentAmount;
}

I am designing a programming that calculates the odds of profiting if you played several scratch- off lottery games

This is the code I have written so far to calculate the odds of profiting from playing lottery scratchers. I have to prompt the user for out output file name (output.txt), where a formatted table with the results will be written. So far my program will output the results, but not in an output file. I am not really sure how to do that or where that will go in my code.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Declaring variables
int lowestAmountOfProfit;
char filename[]="scratcher.txt";
string gameName;
int CostOfTicket, NumberOfPrizes;
int PrizeValue, NumberOfTickets, TicketsNotClaimed;
double RemainingTickets;
double RemainingTicketsForProfit;
double odds;
// The program will ask the user to enter the lowest amount they would like to
// profit when playing the lottery.
cout << "Enter the lowest dollar amount that you would like to profit: "
cin >> lowestAmountOfProfit;
cout << "Enter the output file name: "
cout << "Generating report..."
//open input file
ifstream fin;
fin.open(filename);
//if input file does not exist
if (!fin)
{
// If the input file cannot be found.
cout << "Input file does not exist." << endl;
return 0;
}
//How the output displace will be formatted.
cout << left << setw(25) << "Game" << setw(10) << "Cost" << setw (10) << "Odds" << endl;
cout << "-----------------------------------------------" << endl;
// Reads the name of the game
while (getline(fin, gameName))
{
fin >> CostOfTicket; // Reads the cost of ticket
fin >> NumberOfPrizes; // Reads the number of prizes
RemainingTickets = 0;
RemainingTicketsForProfit = 0;
for (int i = 0; i < NumberOfPrizes; i++)
{
fin >> PrizeValue; // Reads the prize value
fin >> NumberOfTickets; // Reads the total number of tickets
fin >> TicketsNotClaimed; // Reads number tickets not claimed
//regardless of prize value*/
// The following line computes the running sum of the number of tickets remaining for that game.
RemainingTicketsForProfit = RemainingTicketsForProfit + TicketsNotClaimed;
// The next line with compute a sum of the number of remaining tickets where the user would profit.
if (PrizeValue > lowestAmountOfProfit)
{
RemainingTickets = RemainingTickets + TicketsNotClaimed;
}
}
// Tells program what to do if there are zero remaining tickets
if (RemainingTickets==0)
{
// Formats the output
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "Not possible" << endl;
}
else
{
// Tells the program to calculate the odds
odds = RemainingTicketsForProfit / RemainingTickets;
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "1 in " << setprecision(2) << fixed << odds << endl;
}
// Read the blank line
string blankLine;
fin >> blankLine;
}
// Close the input file
fin.close();
return 0;
}
You can output to a file by just declaring it as a ofstream and then basically using it as a cout. Like so:
ofstream outputFile;
outputFile.open("filename.txt");
cout << "Enter the first number: ";
cin >> num1;
outputFile << num1 << endl;
outputFile.close();

How can I get user input to exit a loop?

I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)