C++ undefined reference to `findGrossPay(employeeInfo, double, int)' - c++

A class I've been working on for a few days, running into an error I'm unsure how to fix.
#include <iostream> // for cin, cout, endl
#include <string>
#include <iomanip> // formatting floats
using namespace std;
void programHeader();
void footer();
void printEmployeeInfo(struct employeeInfo);
struct employeeInfo
{
int employeeID;
char employeeName[20];
double payRate;
int employeeType;
};
float findGrossPay(employeeInfo myEmployee, double , int);
void payrollDisplay(employeeInfo myEmployee, double, double, double, float, float);
//prototype declerations
int main()
{
// decleration of variables
float inputNumber1;
int num1;
int num2;
int num3;
int num4;
employeeInfo myEmployee[4];
float totalGross;
float totalNet;
int maxName = 20;
int location;
double hoursArray[4];
double grossPay[4];
double tax[4];
double netPay[4];
// input section
programHeader();
num4 = 0;
location = 0;
for (int c = 0; c < 4; c++) // fill in the array of structs
{
while (true); // validation loop
{
cout << "Employee ID: ";
cin >> num1;
if (num1 > 0);
{
myEmployee[c].employeeID = num1;
break;
} // end if
if (num1 <= 0)
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end else if
} // end while
cout << "Employee Name: ";
cin.getline(myEmployee[c].employeeName, maxName);
while (true); // validation loop
{
cout << "Pay rate: ";
cin >> num2;
if (num2 > 0);
{
myEmployee[c].payRate = num2;
break;
} // end if
if (num2 <= 0)
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end if
} // end while
while (true) // validation loop
{
cout << "Type: ";
cin >> num3;
if ((num3 == 1) || (num3 == 0))
{
myEmployee[c].employeeType = num3;
break;
} // end if
else
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end else
} // end while
} // end for(c)
for (int h = 0; h < 4; h++); // parallel array to hold hours worked
{
cout << "Hours worked for " << myEmployee[num4].employeeName << ": ";
cin >> hoursArray[num4];
num4 = num4 +1;
} // end for(h)
// calculation section
// displays the results
for (int l = 0; l < 4; l++) // l for location
{
grossPay[l] = findGrossPay(myEmployee[4], hoursArray[4], location);
location = location + 1;
} // end for(l)
for (int t = 0; t < 4; t++) // get taxes and net pay for each
{
tax[t] = grossPay[t] * (15 / 100);
netPay[t] = grossPay[t] - tax[t];
}
for (int i = 0; i < 4; i++)
{
totalGross = totalGross + grossPay[i];
totalNet = totalNet + netPay[i];
} // end of for
payrollDisplay(myEmployee[4], grossPay[4], tax[4], netPay[4], totalGross, totalNet);
footer();
system("PAUSE");
return 0;
}// end of main
float findGrossPay(employeeInfo myEmployee[4], double hoursArray[4], int l) // l stands for location
{
float numGrossPay;
if (myEmployee[l].employeeType == 1) // management
{
numGrossPay = myEmployee[l].payRate * hoursArray[l];
} // end if
else if (myEmployee[l].employeeType == 0) // union members
{
if (hoursArray[l] > 40)
{
numGrossPay = myEmployee[l].payRate * 40 + (hoursArray[l] - 40) * (myEmployee[l].payRate * 1.5);
} // end if
else
{
numGrossPay = myEmployee[l].payRate * hoursArray[l];
} // end else
} // end else if
return numGrossPay;
}
void payrollDisplay(employeeInfo myEmployee[4], double grossPay[4], double tax[4], double netPay[4], float totalGross, float totalNet)
{
cout << "------------------------------------------------------------" << endl;
cout << "\nPayroll Report\n" << endl;
cout << "ID \tName" << "\t\tGross Pay \tTax \tNet Pay" << endl;
for (int i = 0; i < 4; i++) // to print each employee
{
cout << myEmployee[i].employeeID << "\t" << myEmployee[i].employeeName << "\t\t" << grossPay[i]
<< "\t" << tax[i] << "\t" << netPay[i] << endl;
} // for(i)
cout << "\nTotal Gross Pay \t$" << totalGross << endl;
cout << "Total Net Pay \t$" << totalNet << endl;
}
It's giving me an error stating there is an undefined reference to these lines in main():
grossPay[l] = findGrossPay(myEmployee[4], hoursArray[4], location);
and
payrollDisplay(myEmployee[4], grossPay[4], tax[4], netPay[4], totalGross, totalNet);

The "undefined reference" errors are because your function declarations do not match their definitions.
You have declared findGrossPay() and payrollDisplay() as taking in a single employeeInfo and related values for that one employee, but then your definitions are taking in arrays of employees and values:
//declaration
float findGrossPay(employeeInfo myEmployee, double , int);
//definition
float findGrossPay(employeeInfo myEmployee[4], double hoursArray[4], int l)
// declaration
void payrollDisplay(employeeInfo myEmployee, double, double, double, float, float);
//definition
void payrollDisplay(employeeInfo myEmployee[4], double grossPay[4], double tax[4], double netPay[4], float totalGross, float totalNet)
As such, the linker can't find matching definitions for the functions you are actually calling.
And, to make that worse, the places where you are calling these functions are accessing array elements out of bounds, which is undefined behavior.
After you fix that problem, you should then get "undefined reference" errors for programHeader() and footer(), since their definitions are missing completely.
After fixing that, there are still other problems with your code:
you have a number of if and for/while loops that have an erroneous ; on them
you are accessing arrays incorrectly in some places
you have uninitialized variables in some of your calculations
With that said, try something more like this:
#include <iostream> // for cin, cout, endl
#include <string>
#include <iomanip> // formatting floats
#include <limits>
using namespace std;
struct employeeInfo
{
int employeeID;
string employeeName;
double payRate;
int employeeType;
};
//prototype declerations
void programHeader();
void footer();
int promptForNumber(const string &prompt, int minValue = 0, int maxValue = numeric_limits<int>::max());
string promptForString(const string &prompt);
float findGrossPay(const employeeInfo &myEmployee, double hours);
void payrollDisplay(const employeeInfo myEmployee[4], const double grossPay[4], const double tax[4], const double netPay[4]);
int main()
{
// decleration of variables
employeeInfo myEmployee[4];
double hours[4];
double grossPay[4];
double tax[4];
double netPay[4];
int num;
// input section
programHeader();
for (int c = 0; c < 4; c++) // fill in the array of structs
{
myEmployee[c].employeeID = promptForNumber("Employee ID", 1);
myEmployee[c].employeeName = promptForString("Employee Name");
myEmployee[c].payRate = promptForNumber("Pay rate", 1);
myEmployee[c].employeeType = promptForNumber("Type", 0, 1);
}
for (int h = 0; h < 4; h++) // parallel array to hold hours worked
{
hours[h] = promptForNumber("Hours worked for " << myEmployee[h].employeeName);
}
// calculation section
for (int l = 0; l < 4; l++) // l for location
{
grossPay[l] = findGrossPay(myEmployee[l], hours[l]);
}
for (int t = 0; t < 4; t++) // get taxes and net pay for each
{
tax[t] = grossPay[t] * (15 / 100);
netPay[t] = grossPay[t] - tax[t];
}
// displays the results
payrollDisplay(myEmployee, grossPay, tax, netPay);
footer();
system("PAUSE");
return 0;
}
void programHeader()
{
// print out something here...
}
void footer()
{
// print out something here...
}
int promptForNumber(const string &prompt, int minValue, int maxValue)
{
int num;
while (true) // validation loop
{
cout << prompt << ": ";
if (cin >> num)
{
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if ((num >= minValue && num <= maxValue)
break;
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "\nERROR PLEASE TRY AGAIN" << endl;
}
return num;
}
string promptForString(const string &prompt)
{
string input;
while (true) // validation loop
{
cout << prompt << ": ";
if (getline(cin, input) && !input.empty())
break;
cout << "\nERROR PLEASE TRY AGAIN" << endl;
}
return input;
}
float findGrossPay(const employeeInfo &myEmployee, double hours)
{
if (myEmployee.employeeType == 1) // management
{
return myEmployee.payRate * hours;
}
// must be myEmployee.employeeType == 0 // union members
if (hours > 40)
{
return myEmployee.payRate * 40 + (hours - 40) * (myEmployee.payRate * 1.5);
}
else
{
return myEmployee.payRate * hours;
}
}
void payrollDisplay(const employeeInfo myEmployee[4], const double grossPay[4], const double tax[4], const double netPay[4])
{
float totalGross = 0.0f;
float totalNet = 0.0f;
cout << "------------------------------------------------------------" << endl;
cout << "\nPayroll Report\n" << endl;
cout << "ID \tName" << "\t\tGross Pay \tTax \tNet Pay" << endl;
for (int i = 0; i < 4; i++) // to print each employee
{
cout << myEmployee[i].employeeID << "\t" << myEmployee[i].employeeName << "\t\t" << grossPay[i] << "\t" << tax[i] << "\t" << netPay[i] << endl;
totalGross += grossPay[i];
totalNet += netPay[i];
}
cout << "\nTotal Gross Pay \t$" << totalGross << endl;
cout << "Total Net Pay \t$" << totalNet << endl;
}
That said, you might consider moving the hours/grossPay/tax/netPay values into the employeeInfo struct, so that you have to manage only 1 array and not 5 parallel arrays.

Related

I'm having trouble with my C++ program using arrays/functions

For my class, I am needing to write a program using arrays instead of individual variables that contain the score. Struggling with this chapter. I'll leave my code below. Any help would be greatly appreciated. Needing to find the sum between all of the scores entered, subtract the highest and lowest and then find the average.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
void getJudgeData(double, double);
double calcScore(double);
double findLowest(double);
double findHighest(double);
int main()
{
// Declare variables
const int SIZE = 7;
double scores[SIZE];
double sum;
for (int x = 0; x < SIZE; x++)
double getJudgeData(scores[x]);
return 0;
}
// Function getJudgeData
void getJudgeData(double &judgeScore, double scores[])
{
static int judge = 1;
cout << "Enter score " << judge << ": ";
cin >> judgeScore;
while (judgeScore < 0 || judgeScore > 10)
{
cout << "Invalid score, please enter a score between 0 and 10";
cout << "Enter score " << judge << ": ";
cin >> judgeScore;
}
judge++;
return;
}
// Function calcScore
double calcScore(double scores[])
{
double highest = findHighest(scores);
double lowest = findLowest(scores);
double result = 0;
for (int x = 0; x < 7; x++)
{
result += scores[x];
}
result - findHighest(scores) - findLowest(scores);
cout << fixed << showpoint << setprecision(2);
cout << "The average after the dropping the highest and lowest scores: " << result / 5 << endl;
return result;
}
// Function findLowest
double findLowest(double scores[])
{
double result = 10;
for (int x = 0; x < 7; x++)
{
if (scores[x] < result)
result = scores[x];
}
return result;
}
// Function findHighest
double findHighest(double scores[])
{
double result = 0;
for (int x = 0; x < 7; x++)
{
if (scores[x] > result)
result = scores[x];
}
return result;
}

assigning a function's output to variables in other function C++

I wrote a code to manage a coffee machine,
I have a function findC that finds the cheapest capsule in the capsule array
a different function of mine findVP that is supposed to use the findC function's output as variables. however, when I pass the variables mp, ind = findC(prices_copy, quantities_copy, SIZE);
and print them it passes them as 0;
but the 2nd cout : cout << findC(prices_copy, quantities_copy, SIZE); prints the correct output.
why is this ? and how can I pass the output of the function to another
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
// Example program
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
#define SLEEVE 10
#define SIZE 10
#define N 5
#define BUDGET 70
//int CapsuleKind[10] = {"JOE","MAC","NES","jamaica","brazil","columbia","MOJO","CLUB","JHON","COF"};
float findMostExpensiveCapsule( float prices[], int size ) // 1
{
float max = prices[0];
int count = 0;
for(int i = 1; i < size; i++)
{
if (prices[i] > max)
{
max = prices[i];
}
}
cout << "The maximum price " << max << " is found on indexes: " ;
for (int i = 0; i < size; i++)
{
if (prices[i] == max)
{
cout << i << " ";
count++;
}
}
cout << endl;
cout << "The maximum number appears " << count << " times." << endl;
return max;
}
int findStrongestCapsuleInStock( int quantities[], int size, int sleeve ) // 2
{
return 0;
}
void SellCapsules( int quantities[], int Qty, int index) // 10
{
quantities[index] = quantities[index] - Qty;
cout << "SOLD " << Qty << " capsules to the Customer, the total now is: " << quantities[index] << endl;
}
float findC( float prices[],int quantities[], int size ) // 9
{
float min = 99999;
int count = 0;
float index=0;
//sort(prices, arr + n);
for(int i = 0; i < size; i++)
{
if (quantities[i] >= SLEEVE)
{
if(prices[i] < min){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
return min, index;
}
void findCheapestSleeve( float prices[],int quantities[], int size )
{
float min = prices[0];
int count = 0;
int index=0;
for(int i = 0; i < size; i++)
{
if (prices[i] < min)
{
if(quantities[i] > SLEEVE){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
}
void showAllCapsulesInStock( int quantities[], float prices[], int size, int sleeve) // 3
{
for (int i = 0; i < size; i++)
{
cout << "capsule kind: " << i << " ---- sleeves available : " << (quantities[i]/sleeve) << " ---- price(for 1 sleeve): " << (prices[i]*sleeve)<< endl;
}
}
float findVP( float prices[], int quantities[], int size, float nis, int sleeve ) //4
{
float mp=0;
float ind =0;
float prices_copy[size];
int quantities_copy[size];
for(int i=0; i<size; i++){
prices_copy[i] = prices[i];
quantities_copy[i] = quantities[i];
}
mp, ind = findC(prices_copy, quantities_copy, SIZE);
cout << "The lowest price sleeve is: " << mp * 10 << " --- the capsule kind is: " << ind <<endl;
cout << findC(prices_copy, quantities_copy, SIZE);
}
void findValueForMoneyPackage( float prices[], int quantities[], int size, float nis, int sleeve )
{
int sleeve_num[size];
float sleeve_price[size];
float min=0;
int index = 0;
int counter=0;
float quant = 0;
for (int i=0; i < size; i++)
{
sleeve_num[i] = (quantities[i]/sleeve);
sleeve_price[i] = (prices[i] * sleeve);
}
//min, quant = findCheapestSleeve(sleeve_price, quantities, 10);
cout << "the cheapest sleeve costs : " << min << " and its of kind :" << quant << endl;
}
void addMoreCapsules( int quantities[], int size ) // 5
{
char answer;
int plus;
for (int i = 0; i < size; i++)
{
cout << "do you want to add capsules to capsule kind " << i << "? (Y/N) " << endl;
cin >> answer;
if (answer == 'Y')
{
cout << "How many capsules do you want to add (inter a number) " << endl;
cin >> plus;
if (plus > 0)
{
quantities[i] = quantities[i] + plus;
cout << "Added " << plus << " capsules to the inventory, the total now is: " << quantities[i] << endl;
}
}
else
{
continue;
}
}
}
// Driver Code
int main()
{
bool flag = false;
int option;
float prices[] = { 1.2, 2.2, 2.5, 1.7, 2.2, 3, 2.8, 2.5, 2.9, 3.7 };
int quantities[] = { 14, 22, 25, 13, 22, 33, 50, 60, 33, 25 };
while (flag != true)
{
cout << "Please choose an option , has to be a number 1-6" << endl;
cin >> option;
if (option == 1)
{
findMostExpensiveCapsule(prices,SIZE);
}
else if ( option == 3)
{
showAllCapsulesInStock(quantities, prices, SIZE, 10);
}
else if (option == 4){
findVP(prices, quantities, SIZE, BUDGET, SLEEVE);
}
else if(option == 5){
addMoreCapsules(quantities,SIZE);
}
else if(option == 9){
findC(prices, quantities, SIZE);
}
else
{
flag = true;
}
}
cout << "GoodBye!" << endl;
return 0;
}
This
return min, index;
doesn't do what you think it does. You obviously think it's going to return two values. But actually it just returns index.
This
mp, ind = findC(prices_copy, quantities_copy, SIZE);
doesn't do what you think it does. You obviously think it's going to assign the two returned values from findC to the variables mp and ind. But actually it's going to return the single value returned by findC to the variable ind and ignore mp.
If you want to know precisely what these constructs do then look up the comma operator, but I guess the moral of the story is that just because you can get some plausible looking code to compile it doesn't mean that it's going to do what you expected it to do.
So the real question is how to return two values from a function in C++. There are actually several possible approaches. Here's a question that reviews some of them, Returning multiple values from a C++ function.

Can't store anything into my arrays

Having trouble storing strings into an array. I tried a multi-dimensional char array but it didn't work. I would ideally like a multi-dimensional string array but every time I try I get the error
cannot convert std::string (*)[100] {aka std::basic_string<char> (*)[100]} to std::string*
Don't even understand what that means. I tried printing the array in my function input_new_student which is where I store the string just to test it, and no luck. The same thing is happening to all my arrays. I've looked it up but I feel like im overlooking something very simple, please help.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
void print_menu();
int get_selection();
std::string get_Name();
float get_GPA();
int get_Year();
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[]);
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[]);
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size);
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum);
using namespace std;
int main()
{
std::string student_names[100];
float student_GPA[100];
int student_start_year[100];
int ramapo_id[100];
int userChoice;
int index = 0;
int size = 0;
float sum = 0.0;
do
{
print_menu();
userChoice = get_selection();
if (userChoice == 1)
{
input_new_student(student_names, student_GPA, student_start_year, index, ramapo_id);
index++;
}
if (userChoice == 2)
{
print_all(student_names, student_GPA, student_start_year, index, size, ramapo_id);
}
if (userChoice == 3)
{
print_by_year(student_names, student_GPA, student_start_year, index, size);
}
if (userChoice == 4)
{
print_statistics(student_names, student_GPA, student_start_year, index, size, sum);
}
if (userChoice == 5)
{
return 0;
}
} while(userChoice > 0 && userChoice < 4);
return 0;
}
void print_menu()
{
cout << "Please pick from the following menu " << endl;
cout << "1. Add a new student " << endl;
cout << "2. Print all students " << endl;
cout << "3. Print students by year " << endl;
cout << "4. Print student statistics " << endl;
cout << "5. Quit" << endl;
}
int get_selection()
{
int userChoice;
cin >> userChoice;
while (userChoice > 4 || userChoice < 1)
{
cout << "Error: Invalid input, please try again: ";
cin >> userChoice;
}
return userChoice;
}
string get_Name()
{
std::string student_name;
cout << "Please enter the student's name: ";
cin >> student_name;
return student_name;
}
float get_GPA()
{
float student_GPA;
cout << "Please enter the GPA: ";
cin >> student_GPA;
return student_GPA;
}
int get_Year()
{
int student_year;
cout << "Please enter the start Year: ";
cin >> student_year;
return student_year;
}
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[])
{
//information generation
srand((unsigned)time(0));
int random_integer = rand();
ramapo_id[index] = random_integer;
//information acquisition
student_names[index] = get_Name();
student_GPA[index] = get_GPA();
student_start_year[index] = get_Year();
}
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[])
{
for (int i = 0; i < size; i++) {
cout << student_names[i] << " - " << ramapo_id[i] << endl;
}
}
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size)
{
int student_year_identifier;
cout << "Which year would you like to display?: ";
cin >> student_year_identifier;
for (int i = 0; i < size; i++)
{
if (student_year_identifier == student_start_year[i])
{
cout << "There were " << index << "students in that year" << endl;
}
else {
cout << "There were no students in that year" << endl;
}
}
}
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum)
{
cout << "Total: " << index << endl;
float avg = 0.0;
for (int i = 0; i < size; ++i)
{
sum += student_GPA[i];
}
avg = ((float)sum)/size;
cout << "GPA: " << avg << endl;
}
I recommend you have a container of structures rather than multiple containers:
struct Student_Info
{
std::string name;
double gpa;
unsigned int starting_year;
}
typedef std::vector<Student_Info> Student_Info_Container;
Student_Info_Container database;
// You could also have an array of student information:
static const size_t MAXIMUM_STUDENTS = 32U;
Student_Info_Container student_information[MAXIMUM_STUDENTS];
Placing the information into a structure support encapsulation and makes the program more efficient.
With parallel arrays, there is a possibility of synchronization issues. For example, the GPA for student 3 may be at index 4 of the array.
If you are restricted to arrays, you would only need to pass 2 parameters to your functions, the array and the capacity of the array.
There are few issues with your code, e.g.:
Your code is difficult to debug because you are using infinite while loops while taking input (e.g. in main and get_selection function).
How would you know if your code is working? At least, print something which indicates that your code is working, like cout << "Student added suuccessfully"; in input_new_student function.
I made these above mentioned changes and you can see that (at least) your code is working for option 1 at http://ideone.com/D5x8Eh
PS: I didn't get that compilation error, you should mention the compiler and flags you are using.
So as an update, the reason I wasn't able to print my array was begin I was not incrementing in my for loop. Thanks to #milesbudnek , #dreschjerm. I was able to see that my code was actually printing by adding the messages, this was prior to the suggestions, but thanks for the suggestion. Here is the code as it is now. Currently I just need to find a way to find values in the array (which I will search for) and create the multi-dimensional array for the strings.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
void print_menu();
int get_selection();
std::string get_Name();
float get_GPA();
int get_Year();
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[]);
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[]);
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size);
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum);
using namespace std;
int main()
{
std::string student_names[100];
float student_GPA[100];
int student_start_year[100];
int ramapo_id[100];
int userChoice;
int index = 0;
int size = 0;
float sum = 0.0;
//seed
srand((unsigned)time(0));
do
{
print_menu();
userChoice = get_selection();
if (userChoice == 1)
{
input_new_student(student_names, student_GPA, student_start_year, index, ramapo_id);
index++;
size++;
}
if (userChoice == 2)
{
print_all(student_names, student_GPA, student_start_year, index, size, ramapo_id);
}
if (userChoice == 3)
{
print_by_year(student_names, student_GPA, student_start_year, index, size);
}
if (userChoice == 4)
{
print_statistics(student_names, student_GPA, student_start_year, index, size, sum);
}
if (userChoice == 5)
{
return 0;
}
} while(userChoice > 0 && userChoice < 5);
return 0;
}
void print_menu()
{
cout << "Please pick from the following menu " << endl;
cout << "1. Add a new student " << endl;
cout << "2. Print all students " << endl;
cout << "3. Print students by year " << endl;
cout << "4. Print student statistics " << endl;
cout << "5. Quit" << endl;
}
int get_selection()
{
int userChoice;
cin >> userChoice;
while (userChoice > 5 || userChoice < 1)
{
cout << "Error: Invalid input, please try again: ";
cin >> userChoice;
}
return userChoice;
}
string get_Name()
{
std::string student_name;
cout << "Please enter the student's name: ";
cin >> student_name;
return student_name;
}
float get_GPA()
{
float student_GPA;
do {
cout << "Please enter the GPA: ";
cin >> student_GPA;
} while(!(student_GPA < 4.0 && student_GPA > 0.0));
return student_GPA;
}
int get_Year()
{
int student_year;
do {
cout << "Please enter the start Year: ";
cin >> student_year;
} while(!(student_year > 1972 && student_year < 2015));
return student_year;
}
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[])
{
//information generation
int random_integer = rand()%900000 + 100000;
ramapo_id[index] = random_integer;
//information acquisition
student_names[index] = get_Name();
student_GPA[index] = get_GPA();
student_start_year[index] = get_Year();
//Notification
cout << endl;
cout << "The student with R# " << random_integer << " was created." << endl;
cout << endl;
}
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[])
{
cout << endl;
for (int i = 0; i < size; i++) {
cout << student_names[i] << " - " << ramapo_id[i] << endl;
}
cout << endl;
}
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size)
{
int student_year_identifier;
//to trigger the response that there ARE students in that year
bool trigger;
int student_count = 0;
cout << "Which year would you like to display?: ";
cin >> student_year_identifier;
for (int i = 0; i < size; i++)
{
if (student_start_year[i] == student_year_identifier)
{
bool trigger = true;
student_count++;
}
}
if (trigger = true) {
cout << endl;
cout << "There are " << student_count << " student(s) in that year" << endl;
cout << endl;
}
else {
cout << endl;
cout << "There are no students in that year." << endl;
cout << endl;
}
}
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum)
{
//Print Total
cout << "Total: " << index << endl;
//Print GPA average
int smart_kids = 0;
float avg = 0.0;
for (int i = 0; i < size; ++i)
{
sum += student_GPA[i];
}
avg = ((float)sum)/size;
cout << "GPA: " << std::setprecision(3) << avg << endl;
//Print # of students above 2.0
for (int i = 0; i < size; i++)
{
if (student_GPA[i] > 2.0)
{
smart_kids++;
}
}
cout << "Above a 2.0: " << smart_kids << endl;
}

Memory Allocation Issues Passing/Returning a Struct *Array

Please help me with my homework. I've got this program working just fine in debug mode, but as soon I use release mode it crashes with an abort().
I know it probably has something to do with memory allocation, but I don't understand pointers well enough.
Requirement is that I have to use an *array to dynamically allocate memory.
"Your program should work for any number of students. When the program
starts, it should ask the user for the number of students to be
processed. Then it should dynamically allocate an array of that size
(array of student/score structures)."
I then need to, "Call a function to input the student name/score pairs and store them in the array."
So should I create the array in main or inside of the function? How can I return/pass the *array without messing up memory allocation?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Student
{
string name; //student's name
int score; //student's score
};
//function prototypes
void inputNameScore(Student*, int&);
void sortArray(Student* , int);
double avgScore(Student* , int);
void displayTable(Student* , int, double);
int main()
{
Student* arrayOfStudentPtr; //pointer of type student to receive returned array pointer
int numberOfStudents; //number of students to be entered by user
double average; //total score average
cout << "Please enter the number of students: ";
cin >> numberOfStudents;
arrayOfStudentPtr = new Student[numberOfStudents]; //dynamic array of type Student assigned to pointer
inputNameScore(arrayOfStudentPtr, numberOfStudents);
sortArray(arrayOfStudentPtr, numberOfStudents);
average = avgScore(arrayOfStudentPtr, numberOfStudents);
displayTable(arrayOfStudentPtr, numberOfStudents, average);
return 0;
}
void inputNameScore(Student* arrayOfStudentPtr, int& numberOfStudents)
{
for (int i = 0; i < numberOfStudents; i++)
{
cout << endl << "Enter the name for student " << i + 1 << ": ";
cin.ignore();
getline(cin, arrayOfStudentPtr[i].name);
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
while (arrayOfStudentPtr[i].score > 105 || arrayOfStudentPtr[i].score < 0)
{
cout << "Student's score can't be negative or greater than 105." << endl;
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
}
}
}
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}
double avgScore(Student* arrayOfStudentPtr, int numberOfStudents)
{
int total; //total of all grades
double average; //average of all grades
total = 0;
for (int i = 0; i < numberOfStudents; i++)
{
total = arrayOfStudentPtr[i].score;
}
average = total / numberOfStudents;
//average = static_cast<double>(total) / numberOfStudents;
return average;
}
void displayTable(Student* arrayOfStudentPtr, int numberOfStudents, double average)
{
cout << endl << setw(31) << left << "Name" << setw(6) << right << "Score" << endl;
cout << "-------------------------------------" << endl;
for (int i = 0; i < numberOfStudents; i++)
{
cout << setw(31) << left << arrayOfStudentPtr[i].name << setw(6) << right << arrayOfStudentPtr[i].score << endl;
}
cout << "-------------------------------------" << endl;
cout << setw(31) << left << "Average: " << setw(6) << right << endl;
}
The following code will work.
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents-1; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}

for loop character printing [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
.....................HEY GUYS,I GOT THE ANSWER.PLEASE CHECK OUT AT BOTTOM.....................
ThAnKs FoR aLl ThOsE wHo TrYiNg tO hElP mE!
How to print all the character outside the for-loop that input inside for-loop? It only prints the last character entered in for-loop
input all 4 names of items and price in void shop::getdata()
output of this only prints the name of item that entered last in void shop::getdata() for 4 times in void shop::putdata()
output of price is correct,it prints orderly.
what's the problem with the name of item?
Question:WAP to store pricelist of 5 items & print the largest price as well as the sum of all prices & pricelist also.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price[50];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
for(i = 0; i <= 4; i++)
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price[i];
}
}
void shop::putdata()
{
cout << "\t\tPRICE LIST" << "\n";
cout << "\t\t**********" << "\n";
cout << "ITEM NAME\t\t\tPRICE" << "\n";
cout << "*********\t\t\t*****" << "\n";
for(i = 0; i <= 4; i++)
{
cout << item << "\t\t\t\t";
cout << price[i] << "\n";
}
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
sum = sum + price[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = price[0];
for(i = 0; i <= 4; i++)
{
if (price[i] > lar)
lar = price[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x;
int c;
clrscr();
x.getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
x.putdata();
break;
case 2:
x.sum();
break;
case 3:
x.lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
ANSWER
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price;
float e[10];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price;
}
void shop::putdata()
{
cout << item << "\t\t\t\t";
cout << price << "\n";
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
cout<<"Enter prices"<<"\n";
cin>>e[i];
sum = sum + e[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = e[0];
for(i = 0; i <= 4; i++)
{
if (e[i] > lar)
lar = e[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x[10];
int c,i;
clrscr();
for(i=0;i<=4;i++)
x[i].getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
for(i=0;i<=4;i++)
x[i].putdata();
break;
case 2:
x[i].sum();
break;
case 3:
x[i].lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
It's a little hard to tell what you're asking (you would do well to indent your code and ask a clearer question), but I think your problem (well, the main one you're referring to!) is how you're handling item names.
You've declared your shop to contain an array of 50 chars - that is, 50 single characters. Since you have an array of 50 prices, you almost certainly wanted an array of 50 strings. In basic C, that would be char *item[50], an array of 50 dynamically-allocated char arrays. Since you've tagged this as C++, though, you're better off using a string.
A slightly more modern shop would look like this:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::ostream;
using std::string;
using std::vector;
class Item {
string m_name;
double m_price;
public:
Item(const string &name, double price)
: m_name(name), m_price(price) {
};
string name() const { return m_name; }
double price() const { return m_price; }
};
class Shop {
vector<Item> m_items;
public:
void readData();
void writeData() const;
double getPriceSum() const;
double getMaxPrice() const;
};
void Shop::readData() {
for (;;) {
string name, end_of_line;
double price;
cout << "Enter the item name (or nothing to finish input): ";
getline(cin, name);
if (name == "") {
break;
}
cout << "Enter the price: ";
cin >> price;
// the previous ">>" left the end-of-line in the stream,
// so read it now.
getline(cin, end_of_line);
m_items.push_back(Item(name, price));
}
}
void Shop::writeData() const {
for (size_t i = 0; i < m_items.size(); i++) {
const Item &item = m_items[i];
cout << item.name() << "\t" << item.price() << "\n";
}
}
double Shop::getPriceSum() const {
double sum = 0.0;
for (size_t i = 0; i < m_items.size(); i++) {
sum += m_items[i].price();
}
return sum;
}
double Shop::getMaxPrice() const {
double max = 0.0; // assume that all prices are positive
for (size_t i = 0; i < m_items.size(); i++) {
max = std::max(max, m_items[i].price());
}
return max;
}
int main() {
Shop shop;
shop.readData();
shop.writeData();
cout << "sum: " << shop.getPriceSum() << "\n";
cout << "max: " << shop.getMaxPrice() << "\n";
return 0;
}
It is not perfect C++ style, but still makes the code easy to read.