This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ passing variables in from one Function to the Next.
The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of paint.
//Problems with this not working
void showMenu();
void getUserData(int &, double &, int &);
void doEstimate(int &, double &, int &, double &, double &);
void showReport();
int main()
{
int choice;
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this int calc ect
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get the user's choice.
showMenu();
cin >> choice;
// Validate the menu selection.
while (choice < 1 || choice > 2)
{
cout << "Please enter 1 or 2: ";
cin >> choice;
}
if (choice == 1)
{
//for some reason it just keeps repeating the function getUserData
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
showReport();
}
} while (choice != 2);
return 0;
}
void getUserData(int &rooms, double &costOfPaint, int &totalsqrtfeet)
{
int sqrtfeet;
int count = 0;
cout << "Please enter the number of rooms to be painted: ";
cin >> rooms;
cout << "Please enter square feet of wall space in each room: ";
cin >> sqrtfeet;
for (count = 1; count <= rooms; count++)
{
cout << "Please eneter square feet of wall space in room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet;
}
cout << "What is the cost of the paint: ";
cin >> costOfPaint;
system("cls");
system("pause");
}
void doEstimate(int &calcGallonsOfPaint, double &calcCostOfPaint, int &calcHoursOfLabor, double &calcLaborCost, double &calcPaintJobCost)
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this: puting int rooms ect
int rooms, totalsqrtfeet;
double costOfPaint;
getUserData(rooms, costOfPaint, totalsqrtfeet);
calcGallonsOfPaint = 1 * (totalsqrtfeet/110); //Calculates the number of whole gallons of paint required.
calcCostOfPaint = calcGallonsOfPaint * costOfPaint; //Calculates the cost of the paint required.
calcHoursOfLabor = calcGallonsOfPaint * 6; //Calculates the number of whole hours of labor required.
calcLaborCost = calcHoursOfLabor * 15.00; //Calculates the labor charges.
//Calculates the cost of the paint job. This is the sum of the labor charges and the cost of the paint required.
calcPaintJobCost = calcLaborCost + calcCostOfPaint;
/*110 square feet of wall space
one gallon of paint
six hours of labor
$15.00 per hour for labor
*/
}
void showReport()
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
cout << "The number of rooms to be painted: " << rooms << endl;
cout << "The number of whole gallons of paint required: " << calcGallonsOfPaint << endl;
cout << "The hours of labor required: " << calcHoursOfLabor << endl;
cout << "The cost of the paint: " << calcCostOfPaint << endl;
cout << "The labor charges: " << calcLaborCost << endl;
cout << "The total cost of the paint job: " << calcPaintJobCost << endl;
system("pause");
system("cls");
}
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-)
On top of that, you call getUserData from your main function and then again from doEstimate. And then you call them both again in showReport. That's why it's asking four times. Just call getUserData once. Since it's homework, I'll leave you to figure out where but here's a hint. If you do it in main (nudge, nudge, wink, wink), you'll have to pass he variables into doEstimate as well, not create new variables of the same name within that function and magically expect the compiler to associate them with the originals.
To caveat on what paxdiablo said, you are calling getUserData in your nested while loop, but I don't understand the purpose of calling getUserData(rooms, costOfPaint, totalsqrtfeet); prior to doEstimate(...) when the data isn't used nor passed to doEstimate(...) until you call getUserData again while inside the doEstimate(...) function. You should pass by value the rooms, costOfPaint, and totalsqrtfeet variables to doEstimate(...) or make them global since you only have one main() function anyways. If you had some sort of OO solution, then I wouldn't recommend making them global and rather part of a class.
Also all these variables are ZERO or NULL when they are passed into doEstimate(...):
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost
If you want to output them, then you need to pass them by reference to doEstimate(...) and then when it gets to the cout then it will sufficiently print the correct values. That is why it is zero.
The bottom line is though you need one function to call the other functions. That would be the simplest plan at this point, such as:
GetDataAndPrint(...) {
// Get some data
// Do estimate, pass in values by reference
// Print Results from calculated values
// return
}
Related
I am a C++ noob.
I am trying to work on this text-based game for school, and I am having trouble with displaying the correct percentage. I think this has to do with how I calculate it in the program, or I am screwing something up with the function.
I would be most grateful for some assistance. Cheers.
#include <string>
#include <cmath>
#include <iostream>
using namespace std;
double menu (float crew_count);
double calculatePct(float crew_count, float number_of_deaths)
{
double percent = ((crew_count - number_of_deaths) / crew_count) * 100;
}
double welcome ()
{
int crew_count;
string backstory = "\nYou are in charge of a top-secret military mission, when your\nspace ship makes an emergency landing, on the largest moon of planet Gork.\nThe space ship is damaged. Oxygen levels begin to drop.\nHow many military personnel are on your ship?\nNumber of personnel: ";
cout << backstory;
cin >> crew_count;
if (crew_count >= 1)
menu(crew_count);
else if (crew_count < 1)
cout << "\nThere must be 1 or more members of the crew! Please enter a valid number!\n";
}
double menu (float crew_count)
{
double percent;
double main_option;
cout << "\nChoose one:\n1. Attempt repairs on the ship.\n2. Request an emergency rescue from mission command.\n3. Break protocol and reveal the top-secret space ship's location,\nto the Russians on a nearby moon, asking for their assistance.\nYour choice: ";
cin >> main_option;
if (main_option == 1)
{
cout << "\nToxic material on the moon has corroded the launch gear, and the \nlaunch exploded!\n\nThere were no survivors.\n";
}
else if (main_option == 2)
{
cout << "\nThe oxygen was depleted before the rescue team arrived.\nThere were 4 people killed.\n";
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
}
else if (main_option == 3)
{
cout << "\nThe Russians agree to send a rescue ship, but secretly attempt to hack into the ships systems remotely, which triggers an automatic shut down of all\ncommunications systems and locks all mission critical storage units, including\none of the storage unit that holds emergency oxygen tanks.\n\nOne quarter of all personnel are lost.\n";
}
else if (main_option != 1, 2, 3)
{
cout << "\nYou have been eaten by a Grue!\n";
}
}
int main()
{
cout << "Welcome to Gork 1.0\nCreated by Cortez Phenix\nTo make selections, enter the number of each option!\n\n";
int choice;
cout << "What would you like to do?\n1. Play Game\n2. Exit\nYour Choice: ";
cin >> choice;
if (choice == 1)
welcome();
else if (choice == 2)
cout << "\nGoodbye!\n";
else
cout << "\nPlease choose 1 or 2.\n";
return 0;
}
Excuse me. I'm sure this post is hectic.
IMAGE: At the bottom, you can see the queer number
If we do some slight reformatting on parts of your code, it looks like this:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
The value you print is not the value calculated by calculatePct, it's the indeterminate value of the percent variable defined earlier in the function.
In short: You forgot your curly-braces:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
{ // Note curly brace here
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
} // And also here
I recommend you enable more verbose warnings, as the compiler should be able to detect that you use the uninitialized variable, as well as the new variable being initialized but not used.
you mixed intergers and floats and void
int crew_count then you fed double menu(float crew_count).
your menu function doesnt return anything its supossed to be void so does your welcome function
Also you calculatePct does not return the calculated percentage. Do that by adding return percent;
See if it helps
c++ and I'm trying to figure out why my code returns 0's from a few statements after the user inputs some float numbers. I'm not sure why. Maybe someone can help:
This is what I get after running my method and answering the questions before it:
The number of gallons of paint required is: 0 gallons
Hours of labor that is required: 0 hours
.
Also ignore the () around my # in the beginning. I will put periods between lines to make it look neater on this website.
/**
* A painting company has determined that for every 160 square feet of wall
space, one gallon of paint and 3 hours of labor are required.
* The company charges the $28.00 per hour for labor.
* Design a modular program that allows the user to enter the number of rooms
that are to be painted,
* the approximate square feet of wall space in each room (may differ from room
to room), and the price per gallon of paint.
* It should then create a report that includes a fancy company header and
displays the following information:
* The number of gallons of paint required: (Rounded up to the next full
gallon)
* The hours of labor required:
* The cost of the paint:
* The labor charges:
* Total cost of the paint job:
* Requirements:
* Input validation: The program should not accept a value less than 1 or
more than 12 for the number of rooms
* Should not accept a value less than 100 for the square
footage of a room.
* Should not accept a value less than $10.00 or more
than $25.00 for the price of a gallon of paint
*
* Lets do this...
*/
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float priceOfGallon(float);
float numberOfGallons(float, float);
float totalWallArea(float, float, float);
float laborHours(float, float);
void fancyCompanyHeader();
int main() {
float area;
float totalArea;
float min_labor = 3;
float number_of_rooms;
float number_of_gallons;
float price_of_gallon;
totalWallArea(area, totalArea, number_of_rooms);
priceOfGallon(price_of_gallon);
numberOfGallons(number_of_gallons, totalArea);
laborHours(number_of_gallons, min_labor);
fancyCompanyHeader();
return 0;
}
// function that gets the number of gallons needed for the total area
float numberOfGallons(float number_of_gallons, float totalArea) {
number_of_gallons = (totalArea / 160.0);
std::cout << "The number of gallons of paint required is: " <<
number_of_gallons << " gallons" << std::endl;
}
float priceOfGallon(float price_of_gallon){
std::cout << "Please enter the price per gallon: " << std::endl;
cin >> price_of_gallon;
while(price_of_gallon < 10.00 || price_of_gallon > 25.00) {
std::cout << "The price should be between $10.00 and $25.00. Please try again: " << std::endl;
cin >> price_of_gallon;
}
}
float totalWallArea(float area, float totalArea, float number_of_rooms) {
std::cout << "Please enter the number of rooms that needs to be painted:" <<
std::endl;
std::cin >> number_of_rooms;
while(number_of_rooms < 1)
{
cout << "Number of rooms must be at least one. Please try again: " <<
std::endl;
cin >> number_of_rooms;
}
for(float i = 1; i <= number_of_rooms; i++)
{
cout << "Please enter the square feet of wall space needed for Room " <<
i << std::endl;
cin >> area;
while(area < 100)
{
std::cout << "The area should be 100 or greater. Please try again: "
<< std::endl;
cin >> area;
}
totalArea += area;
}
}
// I will finish this method later
float laborHours(float number_of_gallons, float min_labor) {
min_labor = number_of_gallons * 28.00;
std::cout << "Hours of labor that is required: " << min_labor << " hours "
<< std::endl;
return min_labor;
}
You need to make all of those variables you are modifying global (Declared outside of int main()). In C++, when you give a function a variable, it will just copy the contents of the variable into the function's variables: the original variable passed in remains constant. Thus, your uninitialized floats default to 0 and are not changed by any of the functions, so when they are given to the laborHours function or numberOfHours function, 0s are passed into each.
Example with much better practices than in your code (it's ok, everyone starts by writing atrocious code) :
#include <iostream>
int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program
void input_walls() {
/* Functions are notated as so in C++:
{return type} {function_name}({input},{input},...)
It's pointless to annotate functions that don't return anything
with a declaration of a float return type (they'll just return 0 */
std::cin >> walls;
while(walls < 0) {
std::cout << "Please input a positive amount of walls per room.";
std::cin >> walls;
}
}
void input_rooms() {
std::cin >> rooms;
while(rooms < 0) {
std::cout << "Please input a positive amount of rooms";
std::cin >> rooms;
}
}
void calculate_result() {
total_walls = walls*rooms;
}
void output_result() {
std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}
int main() {
input_walls();
input_rooms();
calculate_result();
output_result();
}
This still isn't the best way to write this, but it's still the exact same thing you were trying to do. Now try rewriting what you were trying to do in this style!
TLDR/Quick fix: Make the variable definitions global, cut out the arguments from the functions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
int main()
{
double tuitionCalc(int sumCreditHoursTaken);
int numCourses;
double total = 0.0;
double tuitionCost= 0.0;
cout << "\t\t This Program calculates a student's total number of\n";
cout << "\t\tcredit hours and tution for a given semester.\n";
cout << "\nPlease enter the number of Courses you will be taking this semester: ";
cin >> numCourses;
for ( int count = 1; count <= numCourses; count++)
{
double sumCreditHoursTaken;
cout << " please enter the number of credit hours for course" << count << ": ";
cin >> sumCreditHoursTaken;
total += sumCreditHoursTaken;
}
cout << fixed << showpoint << setprecision(2);
cout << "Your Total number of credit hours is: " << total << endl;
cout << "Your total tuition will be: $" << tuitionCalc(tuitionCost) << "\n\n";
return 0;
}
and the function im calling is
double tuitionCalc(int sumCreditHoursTaken)
{
double tuitionCost = 0.0;
double costCreditHour = 147.00;
double maxHoursFullTuition = 12;
double maintFeeAddOn = 29.33;`
if (sumCreditHoursTaken <= maxHoursFullTuition)
cout<< " " << (sumCreditHoursTaken * costCreditHour);
else if (sumCreditHoursTaken > maxHoursFullTuition)
cout << " " << (maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
}
input for number of courses is 5
and credit hours is 3,3,3.5,4,2.5
i get the total credit hours but icant seem to display the tuition cost?
thank you s
You are never actually assigning a value to tuitionCost in tuitionCalc() method, so it will always be 0.0.
To elaborate: You are returning tuitionCost from tuitionCalc(). You first initialize tuitionCost = 0.0, but never proceed to assign any calculated value to it. Thus, when you return tuitionCost, it will return the value you initialized it to: 0.0.
I haven't examined your code in detail, but if you inputs contain floating point numbers then change the type for sumCreditHoursTaken from int to double.
Also, change the parameter for the invocation of tuitionCalc from tuitionCost to total.
It seems that OP has fallen afoul of misunderstanding scope and how variables are passed to functions.
In main, OP defines tuitionCost. tuitionCalc defines another tuitionCost. These are different tuitionCosts. They represent different locations in memory and can store different values.
Next, because the tuitionCalc function is defined
double tuitionCalc(int sumCreditHoursTaken)
tuitionCalc(tuitionCost) will take tuitionCost convert it to an integer, and pass a copy into tuitionCalc where it will be used with the name sumCreditHoursTaken. One could say OP has three tuitionCalcs at this point. Not what they want.
Breaking down the tuitionCalc prototype, we see that it takes sumCreditHoursTaken, an integer and based on the name the number of credit hours taken, not a total cost. tuitionCalc also returns a double and inferring the purpose of the function from it;'s name, one would expect that it calculates and returns the tuition.
Like Anatoly states in his answer, the input to tuitionCalc should almost certainly be total, the total number of credit hours computed, and the output should be tuitionCost.
Since this has the smell of a homework assignment, it's not in the OP's best interests to fully answer the question. Instead here are a few recommendations:
Eliminate tuitionCost from main. It only serves to increase confusion. You can reuse variable names, but only do it where there is a clear benefit. If you have a cost and a function that takes and uses cost, then using cost for both makes sense. Just remember that cost inside the function is a different entity unless you pass by reference. In
void function(int & cost)
called with
function(cost);
both costs are the same. But in
void function(int cost)
called with
function(cost);
both function's cost is a copy of the caller's cost and any changes made by function will only effect the copy.
Declare variables close to where you use them. This way people reading your code don't have to scroll up and down and otherwise go hunting. It also helps you because it makes mistakes like, "Why am a calling a function that takes an int with a double?" more obvious.
Do not cout in tuitionCalc. Compute and return tuitionCost. Allow main to output tuitionCost. A function with a name like calc should only calculate. Names should describe function as closely as possible.
First of all you should create the function prototype before declaring it.
And there were some confusions in the code you have used I tried my best to omit error hope this is helpful!
#include <iostream>
#include <iomanip>
using namespace std;
double tuitionCal(double sumCreditHoursTaken);
int main() {
double tuitionCalc(int sumCreditHoursTaken);
int numCourses;
double total = 0.0;
//double tuitionCost= 0.0;
cout << "\t\t This Program calculates a student's total number of\n";
cout << "\t\tcredit hours and tution for a given semester.\n";
cout << "\nPlease enter the number of Courses you will be taking this semester: ";
cin >> numCourses;
double sumCreditHoursTaken; // you should create this variable outside the for loop
for ( int count = 1; count <= numCourses; count++)
{
cout << " please enter the number of credit hours for course" << count << ": ";
cin >> sumCreditHoursTaken;
total += sumCreditHoursTaken;
}
double tuitionCost=tuitionCal(total);
cout << fixed << showpoint << setprecision(2);
cout << "Your Total number of credit hours is: " << total << endl;
cout << "Your total tuition will be: $" <<tuitionCost<< "\n\n";// I assume this is what you want
return 0;
}
double tuitionCal(double sumCreditHoursTaken)//the parameter type is double now
{
double tuitionCost = 0.0;
double costCreditHour = 147.00;
double maxHoursFullTuition = 12;
double maintFeeAddOn = 29.33;
if (sumCreditHoursTaken <= maxHoursFullTuition)
tuitionCost=(sumCreditHoursTaken * costCreditHour);
else if (sumCreditHoursTaken > maxHoursFullTuition)
tuitionCost=(maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
//I don't see a point of returning the value and couting both you can
//do only one of the oprations
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm posting because I'm having issues figuring out why my "total aid available" is not printing the total of the pell grant, stafford loan, and work-study loan. I've tried fixing my function again and again (I used sources online and in reference book, but I don't know if the issue is that my function won't be called or not, since nothing is printing for the total aid available.
Everything else is fine, except that one thing, and it is really bugging me since no matter what changes I make, I'm in the same state. No errors showing either. I'm using microsoft visual studio for the first time as compiler, so I wonder if that is the issue.
Here is what I have:
#include <iostream>
using namespace std;
double pell_Grant(double); // forward declaration on pell_Grant ( which is a function for calculating pell grant)
double sum(double, int const, double); // declaration for sum function which gives total for the total aid available
int main()
{
double workstudy = 0, pellgrant = 5730, grossincome = 0, Total = 0; // variables
int yes;
int const stafford = 9500; //const declaration
cout << "Lemme Forecast Your FAFSA" << endl;
cout << "Enter your adjusted gross income: " << endl; cin >> grossincome; // input for gross income
if (grossincome >= 30000) // if gross income is higher than 30,000 then print message
{
cout << "Sorry Charlie, your income is too high to run this forecaster!";
return 0;
}
cout << "Can someone claim you as a dependent? [1=yes/0=no]: " << endl; // input to claim dependent or not
cin >> yes;
if (yes == 1) // if 1 for yes is selected then pell grant gets reduced by 750, if 0 or no selected, then program goes by standard procedure
{
pellgrant -= 750;
}
workstudy = 1465; // work study must be nationwide avergae 1,465
if (grossincome >= 19000) // if this condition is met then work study is not met and message is printed as follows...
{
cout << "Your Work-Study Award is not available for your income level" << endl;
workstudy = 0;
}
double foo = pell_Grant(grossincome); // value returned from pell_Grant stored here to give total
Total = sum(workstudy + stafford + pellgrant); // sum function is called and stores result in Total
if (workstudy != 0) // if work study loan isn't more than 19,000 then it will be calculated and printed in next statement
{
cout << "Your Work-Study Award (if available)= " << workstudy << endl;
}
cout << "Your Stafford Loan award (if needed)= " << stafford << endl; // prints stafford loan (const called)
cout << "Your Pell Grant= " << pellgrant << endl; // prints pell grant
cout << "Total Aid Available For You=" << Total << endl; // prints total
return (0);
}
double pell_Grant(double x) // pell_Grant function that calculates pell grant which is assigned 5,730
{
// x is gross income which is assigned 5,730. This is money received that does not need to be repaid.
if ((x > 12000) && (x < 20000)) // statement makes sure adjusted gross is bettween 12000 & 20000
{
double a = x / 1000; // for every 1,000 in adjusted gross income... reduce/subtract 400 from it
a *= 400;
x -= a;
}
if (x > 20000) // check if gross income is more than 20000
{
double a = x / 1000; // for every 1,000 in gross income, subtract 500
a *= 500;
x -= a;
}
return x;
}
double sum(double workstudy , int const stafford, double pellgrant) // function for adding up workstudy loan, stafford loan, and pellgrant loan
{
double Total;
Total = workstudy + stafford + pellgrant;
return (Total); // returns total
}
According to its declaration, the method sum() accepts 3 parameters.
double sum(double, int const, double);
But while calling you are passing only 1 parameter:
Total = sum(workstudy + stafford + pellgrant);
Instead, you need to pass 3 parameters, like this:
Total = sum(workstudy, stafford, pellgrant);
But, I don't understand why you aren't getting any errors! You are trying to call a non-existent function. You must get a compiler error.
You are calling your sum() function incorrectly. This is your code:
Total = sum(workstudy + stafford + pellgrant); // sum function is called and stores result in Total
But your sum() function has three parameters. The correct form to call the function would be:
Total = sum(workstudy, stafford, pellgrant); // sum function is called and stores result in Total
I'm really confused. I have to make this lab for a class and I can't seem to have the search only display one result but all of the months of the year. I also can't seem to figure out why its not displaying the TotalRainfall when I input 0 into the month of the year.
Thank you.
#include <iostream>
#include <fstream>
const int MaxSize = 12; //How many weather lines will be available.
using namespace std;
struct WeatherInformation
{
int Month; //Months of the year
float TotalMonthsRainfall; //Total amount of rainfall
float HighTemp; //The Highest temperature of the month.
float LowTemp; //The Lowest temperature of the month.
float AverageTemp; //The Average temperature of the month.
};
WeatherInformation WeatherArray[MaxSize]; //Declaring a month array of MaxSize
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[]);
void WeatherMonthSearch (WeatherInformation WeatherArray[]);
int main()
{
float TotalRainfall = 0;
int count = 1; //Counts how many times the for loop goes.
int MonthOfWeather; //User input of the month.
char ProgramRedo; //User input if they want to reuse the program.
char exit_char; //User input to exit the program.
ifstream MyinFile; //Variable that uses file.
ReadFile (MyinFile, WeatherArray); //Call ReadFile Function
WeatherMonthSearch (WeatherArray); //Call WeatherMonthSearch Function
MyinFile.close(); //Closes file.
}
//Brett Holmes
//4/30/2013
//PreCondition:You need a file labeled weather.dat
//PostCondition: It puts the file variables into an array.
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[])
{
float TotalRainfall = 0;
char exit_char;
int count = 0;
int Month = 0;
cout << "Your Weather Machine" << endl << endl;
MyinFile.open("weather.dat");
if (!MyinFile)
{ //no
cout << "Can't open input file." << endl; //Tests the right file.
char exit_char; //End Program
cout << "Press any key to exit" << endl;
cin >> exit_char;
}
for(count = 1; count < MaxSize; count++) //Puts the file variables in the array.
{
WeatherArray[count].Month = WeatherArray[count].Month + 1;
MyinFile >> WeatherArray[count].TotalMonthsRainfall;
MyinFile >> WeatherArray[count].HighTemp;
MyinFile >> WeatherArray[count].LowTemp;
(WeatherArray[count].AverageTemp = ((WeatherArray[count].HighTemp + WeatherArray[count].LowTemp)/2));
(TotalRainfall = TotalRainfall + WeatherArray[count].TotalMonthsRainfall);
}
}
//Brett Holmes
//4/30/13
//PreCondition:You need to have the months already put into an array in a struct.
//PostCondition:Outputs the rainfall stats the user puts in then asks to run again.
//Outputs a error message if they type in the month wrong.
void WeatherMonthSearch (WeatherInformation WeatherArray[])
{
float TotalRainfall;
int months;
int MonthOfWeather;
char ProgramRedo;
do
{
bool MonthFound = false;
cout << "Please input the number of the Month. Ex. 1=Jan. 2=Feb. etc \n\n";
cin >> MonthOfWeather;
for(int i = 1; i <= MaxSize; i++)
{
months = WeatherArray[i].Month;
if(months == MonthOfWeather ) //Finds the artist and outputs the results
{
cout << "\nTotal Months Rainfall: " << WeatherArray[i].TotalMonthsRainfall << " \n";
cout << "Highest Temperature: " << WeatherArray[i].HighTemp << " \n";
cout << "Lowest Temperature: " << WeatherArray[i].LowTemp << " \n";
cout << "Average Temperature: " << WeatherArray[i].AverageTemp << " \n";
MonthOfWeather = true;
}
}
if(MonthOfWeather == 0)
{
cout << "The total rainfall for the year is: " << TotalRainfall << ".";
}
if(MonthFound == false)
{
cout << "\nMonth Number error. Month not found. Try again.\n\n";
MonthOfWeather = false;
}
cout << "Would you like to look up another month of weather?\n";
cout << "Enter a 'Y' if yes and 'N' if no.\n";
cin >> ProgramRedo;
}while(ProgramRedo == 'Y');
}
Several obvious problems:
Arrays in C++ is 0-based, so your for loop is off-by-one. In your search function, for(int i = 1; i <= MaxSize; i++) should be for(int i = 0; i < MaxSize; i++). Similarly, in your read function, for(count = 1; count < MaxSize; count++) should be for(count = 0; count < MaxSize; count++) (If you want to skip index 0 because you are using it as a signal value, then you should set MaxSize to 13 and have the loop start at 1.)
Why are you assigning a boolean to MonthOfWeather? Do you mean MonthFound?
You read function is not setting the months correctly. WeatherArray[count].Month = WeatherArray[count].Month + 1; should be WeatherArray[count].Month = count; if you are using a 1-based loop or WeatherArray[count].Month = count + 1; if the loop is 0-based.
You calculated your total rainfall in the read function, but the result is stored in a local variable so it's lost when the read is done. Either make TotalRainfall a global variable or do your calculations in your search function.
There are a lot of redundant variable definitions: for example, your weather data array is a global so there is no reason to actually pass it around; exit_char is declared twice in your read function; the first five lines of your main() declared variables that you never used.
Also, your read function does not actually exit the program on failure - it even still attempts to read from the stream and then call your search function! If error-checking is a requirement, you should either have the read function return a boolean and check that the read function succeeded before calling your search function, or simply call std::exit after that cin >> exit_char;.
So, one problem you have is that you have local variables that appear in multiple places, but appears like you expect them to actually contain the same information.
For example, I see three different TotalRainFall. One in main, which is just there, not used for anything, one in ReadFile which is calculated, and one in WeatherMonthSearch, which is not set to anything.
I suspect you want all three of these to actually do something. One way to achieve that would be to remove the local ones in ReadFile and WeatherMonthSearch, and instead pass in the one from main (as a reference into ReadFile).
There's also a few places where you use variables without initializing them. Make it a habit to initialize EVERYTHING and EVERYWHERE!
Enable warnings in your compiler - if you have any form or reasonably new compiler (gcc or MS Visual Studio of recent vintage), it should tell you at least some of these things.