Need help passing arrays, and input arrays - c++

So this is a topic that is often confused, the arrays are always passed by reference.
The point of this program is to have a company figure out how much food their kittens are eating weekly.
So the program works well however whenever I go to send my food values ,,, that the use inputs themselves, (these are the amounts of food each kitten is eating weekly), its sending back values that arent what i'm trying to pass, theyre just random numbers in memories, and i assumed that its because im not returning a value, but i read that these values are passed by reference and that you do not need to return a value,
Please help!
#include <iostream>
using namespace std;
void kittyfood(string kittyNames[], int sizeOfArray); //prototype for kittyfood function
void report(string kittyNames[], int sizeOfArray, float food[]); //prototype for report function
int main()
{
string names[5]={"Fluffy","Sneaky","Moonie","Stuffy","Oriana"}; //set cat names to the array
float food[5]; //float array for food amounts with 5 elements
kittyfood(names,5); //call too kittyfood function passing the kitty names and the size of array
report(names,5,food); //call to report function with kitty names, size of array, and ammount of foods
return 0;
}
void kittyfood(string kittyNames[], int sizeOfArray)
{
float food[5];
for (int i=0;i<sizeOfArray; i++) //loop to go through cat names and get the amounts of food they eat
{
cout << "Please enter the amount of food in pounds "<< kittyNames[i] << " eats weekly\n"; //prompt user food eaten
cin >> food[i]; //user input food eaten
while (food[i]<0)
{
cout << "This cannot be a negative ammount \n"; //input validation
cin >> food[i];
}
}
}
void report(string kittyNames[], int sizeOfArray, float food[])
{
float smallest, largest; //declaration for the smallest and largest amount
string smallestName, largestName; //declaration for the cat that eats the most or least
smallest=largest=food[0]; //initialize the smallest and largest at the first array food value
smallestName=largestName=kittyNames[0]; //initialize for the smallest and largest eaten for the first cat name in array
float totalFood; //declaration
totalFood=0; //initialization
for (int i=0;i<sizeOfArray; i++) //loop to go through cats and display their name and amount of food they ate
{
cout << kittyNames[i] << " eats "<< food[i]<< " pounds of food weekly \n";
if (smallest > food[i])
{
smallest = food[i]; //if the food amount is less than the original value then replace it
smallestName=kittyNames[i]; //change the name of the cat to the new cats name
}
if (largest < food[i])
{
smallest = food[i]; //if the food amount is more than the original then replace it
largestName = kittyNames[i]; //change the name of the cat to thew new cats name
}
totalFood+=food[i]; //keep adding the amounts of food to the total each time the loop goes through
}
cout << endl<<smallestName << " ate the least amount of food at " << smallest << " pounds \n"; //display the lowest cats name + ammount
cout << largestName << " ate the most amount of food at " << largest << " pounds \n"; //display the largest cats name + ammount
cout << "The total amount of food eaten weekly is "<<totalFood<<endl; //display total food eaten
}

The problem is that food inside the kittyfood function is a local variable and not the same as the array you have created in your main function.
The local variable gets destroyed after the function has returned and the one on main is still uninitialized thus containing garbage values.

The food array in main is not the same as the food array in kittyfood. In kittyfood you're populating a local to the function array with some values. As a result the array in main has undefined contents.
You could pass the food array to kittyfood as well, like so:
int main()
{
string names[5]={"Fluffy","Sneaky","Moonie","Stuffy","Oriana"};
float food[5];
kittyfood(names, food, 5);
}
void kittyfood(string kittyNames[], float food[], int sizeOfArray)
{
// populate the food array
}
Or you could use std::vector or std::array to make your life easier, but that is beside the question.

You read amount of food (float food[5]; variable) from standard input in kittyfood function and never use it. I guess this will help you.
void kittyfood(string kittyNames[], int sizeOfArray, float food[])
{
for (int i=0;i<sizeOfArray; i++) //loop to go through cat names and get the amounts of food they eat
{
cout << "Please enter the amount of food in pounds "<< kittyNames[i] << " eats weekly\n"; //prompt user food eaten
cin >> food[i]; //user input food eaten
while (food[i]<0)
{
cout << "This cannot be a negative ammount \n"; //input validation
cin >> food[i];
}
}
}

Related

How do I make my program pass data to my array correctly? (Homework)

I've set my array size to 20 (I set it to 19 assuming it's counting 0). I set my for loop to only run so long as gradeCount <= to gradeCounted yet it will keep running no matter how many times I enter data. If I enter 3 grades without pressing enter between each one, such as "23 23 23" it will return "Enter Grade" 3 times in a row, rather, for as many grades as I enter, separated by spaces. I don't understand why it's not passing data into the array and ending the for loop properly. I'm sure my code is an ugly mess, sorry.
Also, when entering code into stackoverflow, it said to indent the code 4 spaces to format? I couldn't initially indent the code with the code button and there was no {} button either. What am I missing? It was only after a notification to fix it that I was able to. Thanks for your time, I don't want to be a pain in the ass for you guys.
//This program asks user how many grades there are, inputs grades, and displays median of said grades.
#include <iostream>
using namespace std;
//Variables
////////////////////const int limitGrades = 20; //Array "boxes"? //Ignore this //for now.
int gradeCounted; //Number of grades from user.
const int SIZE = 19;
//Array
float grades[19]; //Max grades that can be entered.
//Functions
void gradeTaker()
{
cout << "You may input up to 20 grades. \n";
cout << "First enter the number of grades you have: \n";
cin >> gradeCounted;
//requests how many grades there are and stores them in array
for (int gradeCount = 0; gradeCount <= gradeCounted + 1; gradeCount++)
{
for (float &grade : grades)
{
cout << "Enter grade: \n";
cin >> grade;
}
}
};
int main()
{
gradeTaker();
cout << "grades so far";
for (int grade : grades)
cout << grade << endl;
system("pause");
}
The size of the array is separate from how you access it. Accessing 20 values is the equivalent to accessing indices from 0 to 19.
float grades[20];
for(size_t i = 0; i < 20; i++){ // print all values of grades
std::cout << grades[i] << "\n";
}
Furthermore, your for loop in gradeTaker will ask you for a value for each index of grades a total of gradeCounted + 2 times. To fix this, only iterate over the indices that you're assigning a value to like so:
for (int gradeCount = 0; gradeCount < gradeCounted; gradeCount++){
cout << "Enter grade: \n";
cin >> grade[gradeCount];
}
Finally... the for loop in your main function will iterate across the entire array which may include uninitialized values. You should initialize the array or use a dynamic data structure like std::vector and just push_back the necessary values.
(P.s. highlight code in the text-block and press CTRL+K to indent.)

how do i print the double variable inside or outside the for loop

I am doing a project on hotel occupancy but I am having a difficulty in printing the double variable. I need to know how to display the double variable using setprecision.
#include <iostream>
using namespace std;
int main()
{
int numfloors=0; //for number of floors
int numrooms=0; //for number of rooms per floor
int numoccipied=0; //for rooms that are occupied
int TRooms=0; //for total rooms in hotel
int TOcuppied=0; //for total rooms occupied in the hotel
int TUnoccupied=0; //for unoccupied rooms in the hotel
double occupancy=0; //for persentage occupancy
cout<<"Enter the number of floors in the hotel"
<<"\nNote: please do not write value less than 1: ";
cin>>numfloors;
for(int floor=1; floor<=numfloors; floor++) //loop starts
{
cout<<"how many rooms are there in no."<<floor<<"floor?\n"; //ask user to for number of rooms per floor
cin>>numrooms;
TRooms+= numrooms; //total rooms in each floor will add and store in Trooms
cout<<"how many rooms are ocupied?\n"; //ask user to put number of occupied rooms
cin>>numoccipied;
TOcuppied+=numoccipied; //number of rooms occupied per floor is added
TUnoccupied=TRooms-TOcuppied; //stores all unoccupied rooms
occupancy=(TOcuppied)/TRooms; //store persentage occupancy
cout<<"\n\nThe Hotel has "<<TRooms<<"rooms\n";
cout<<"from which "<<TOcuppied<< " rooms are occupied,\n";
cout<<"and "<<TUnoccupied<<" are Unoccupied.\n ";
}
cout << fixed << showpoint << setprecision(1);
cout<<"\n\nOccupancy Rate: "<<occupancy*100<<"% \n\n";
return 0;
}
You seem to be a beginner so I'll list some problems with your code:
When dividing two integers, the result is also an integer. So, in integral division, 4/10 is 0. This line, therefore, always produces zero:
occupancy=(TOcuppied)/TRooms;
Instead use:
occupancy=(TOcuppied)/(double)TRooms;
The settings for cout must obviously all come BEFORE the input. So first send the settings:
cout << fixed << showpoint << setprecision(1);
Then:
cout << occupancy*100;
Of course, you can put it on one line:
cout << fixed << showpoint << setprecision(1)<< occupancy*100;
You're allowing some kinds of invalid output. Since yours look a lot like homework assignment, you might need to sanitize those. One is that you allow one to enter more occupied rooms than available:
how many rooms are there in no.1floor?
10
how many rooms are ocupied?
20
The Hotel has 10rooms
from which 20 rooms are occupied,
and -10 are Unoccupied.
Occupancy Rate: 200.00%
So remember to check that input:
if(numoccipied>numrooms) {
// do something, such as asking the user to enter correct value
}
Similarly, you should prevent user from entering less than 1 floor:
if(numfloors<1)
return 0;

double functions, fstreams, and more fun

The big picture is to take information from one file to another file. I've done that and it works well. The next thing I need to do is find the highest value from the new file. The basic format is like this: I have a bunch of "workers", I have the days they have worked, the hours & minutes they've worked. In the new file I have it formatted to show the pay rate (I enter the value as a cin) and then I have the total amount of money they made (everyone makes the same amount.. that which is in the cin). For some reason, I cannot make a function (that works) that will extract the persons name that makes the most money, and how much money that is. I got a little frustrated and was trying whatever I could so the new function is sloppy and ridiculous, but I was hoping you could help. To keep this a general question and not a specific question, I was wondering if you guys could just explain how to do something like this (finding the highest value & outputting it WITH the name of the person.. so essentially a double for the money and a string with the persons name) using parts of my code as an example:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
void getandprintaddress (ifstream&, ofstream&); // this function will be used to get the data from one file and input it into the next with the total amount of money made from each person as well as the next function
double highestpaid(double& highesttotal, double& totalpay, string highestpaidemp, string name); // this function is what will be used to find the highest amount of money and the person who has it
void name(); // This is to input my name in the file.
struct employees // This is the structure with all of the information that will be used to calculate everything.
{
string name; // person's name
string highestpaidemp; // highest paid employee
string address; // the address of the employee
string address2;
int days; // days worked
int hours; //hours worked
double minutes; // minutes worked
int total_hours; // total hours worked
double totalpay; // total pay
double payrate; // pay rate
double total_minutes; // minutes worked
double total_time; // total hours and minutes worked
double highesttotal; // the highest total amount of money made between all employees.
};
int main(){
ifstream inputFile;
ofstream outputFile;
getandprintaddress(inputFile, outputFile);
return 0;
}
void getandprintaddress(ifstream& inputFile, ofstream& outputFile) // the main function that will be used to get and output all the information.
{
struct employees();
ifstream getdata;
ofstream outdata;
int employees_t;
employees employeeinfo;
string inputfile;
string outputfile;
cout << "What is the name of your input file? "<<endl; // this will be the file you open
cin>>inputfile;
getdata.open(inputfile.c_str());
if(getdata.fail()){ // this is meant to be used if someone enters a file that isn't there
cout << "The input file has failed to open. \n";
exit(1);
}
cout << "What is the name of your output file? \n"; // what you want the title of the new file to be.
cin>>outputfile;
outdata.open(outputfile.c_str());
if(outdata.fail())
{
//This is if the new file is invalid
cout << "The outputfile failed to open. \n";
exit(1);
}
cout << "How many employees are there? \n" ;
cin >> employees_t; // Enter how many employees there are
cout << "What is the employees hourly payrate? \n";
cin >> employeeinfo.payrate; // how much each employee makes.
for ( int info = 0; info < employees_t; info++)
{
employeeinfo.highesttotal = 0.0; // this will be needed for calculating the highest paid employee
employeeinfo.total_minutes = 0.0; // This is needed to calculate total minutes
employeeinfo.total_hours = 0; // Same as the total_minutes, but for hours instead.
employeeinfo.total_time = 0.0; // Needed to calculate total time
string line1;
getline(getdata, employeeinfo.name);
outdata << "Name: " << employeeinfo.name <<endl; // employees name
getline(getdata, employeeinfo.address);
outdata << "Address: \n"; // Employees address
outdata<< employeeinfo.address <<endl;
getline(getdata, employeeinfo.address2);
outdata <<employeeinfo.address2 <<endl;
getdata >> employeeinfo.days;
outdata << "Days worked: " <<employeeinfo.days << endl; // Days worked
for (int totalworked=0; totalworked<employeeinfo.days; totalworked++)
{
// Because the employees work different amount of days, this loop is needed to post the individual information from each employee
getdata >> employeeinfo.hours >> employeeinfo.minutes;
employeeinfo.minutes = employeeinfo.minutes / 60;
employeeinfo.total_hours = employeeinfo.total_hours + employeeinfo.hours;
employeeinfo.total_minutes = employeeinfo.total_minutes + employeeinfo.minutes;
employeeinfo.total_time = employeeinfo.total_minutes + employeeinfo.total_hours;
employeeinfo.totalpay = employeeinfo.total_time * employeeinfo.payrate;
outdata << employeeinfo.hours <<" hours "<< employeeinfo.minutes*60 << " minutes"<< endl;
}
outdata << fixed << showpoint << setprecision(1); // Setting the total hours worked to 1 decimal so that to include the minutes
outdata << "Total hours worked: "<<employeeinfo.total_time<<endl; // Total hours worked
outdata << fixed << showpoint << setprecision(2); // Setting the decimal to two places
outdata << "Hourly pay: $"<<employeeinfo.payrate << endl; //Hourly pay
outdata << "Gross pay: $" <<employeeinfo.totalpay <<endl; // Gross pay
getline(getdata,line1);
getline(getdata,line1);
outdata << "\n";
double highestpaid(employeeinfo.highesttotal, employeeinfo.totalpay);
}
};
double highestpaid(double& highesttotal, double&totalpay, string highestpaidemp, string name)
{
if (highesttotal < totalpay)
{
highesttotal = totalpay;
highestpaidemp = name;
}
return highestpaid(double& highesttotal, double&totalpay, string highestpaidemp, string name);
};
Ok, I'm going to answer your general question rather than spend too long searching through your code, but hopefully should work for both.
You have your struct employee
Stick them all in a vector of employees (which i'll call workers)
vector<struct employee> workers
using a vector means you can just keep on adding more to the end, but an array would work too if you had a fixed number of workers
now each worker can be identified by an integer index, 0 to n-1, where n is number of workers. Now can just iterate through (quicker methods if very large number of workers but probably fine here) to find highest salary
double highestPay = 0;
int highestPaidIndex = 0;
for(int i = 0; i++; i < n)
{
if(workers[i].totalpay > highestPay)
{
highestPay = workers[i].totalpay;
highestPaidIndex = i;
}
}
Now highestPaidIndex is the index of the highest paid employee, who has name workers[highestPaidIndex].name and total earnings workers[highestPaidIndex].totalpay
Hope that solves both your general and specific question

How to input values after for loop in C++?

I have to make a program which inputs 10 student's grades and displays their weighed and unweighted averages. I am new to C++ programming so I don't know much and my professor doesn't like it when people use things he hasn't taught.
Here's the code: It shows up as What are the four test scores of student 1,2, etc. How can I make it to be when it says "What are the four test scores of student 1", then I would be able to enter those in. And then on to student2, student3, etc?
Thank you for your time.
#include <iostream>
using namespace std;
const int numberofstudents = 10;
int main()
{
int student;
for(student=1; student<=numberofstudents; student++)
cout << "\nWhat are the four test scores of student number " << student << endl;
return 0;
}
I think you want to read four values for each students, if so , then understand this code:
#include <iostream>
using namespace std;
int main()
{
const int numberofstudents = 10;
double scores[numberofstudents][4];
for(int student=0; student<numberofstudents; student++)
{
cout << "\nWhat are the four test scores of student number " << (student+1) << endl;
int i = 0;
while ( i < 4 )
{
//scores is a two dimentional array
//scores first index is student number (starting with 0)
//and second index is ith score
cin >> scores[student][i]; //read score, one at a time!
i++;
}
}
//process scores...
}
Now since it's your homework, do the rest of your work yourself. All the best!

C++ Functions and Passing Variables [duplicate]

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
}