I am studying BscCS so I am familiar with programming concepts, however I always seem to get stuck on structs and arrays of structs.
I am required to convert parallel arrays into an array of structs. I have done this, but for some reason the information is not getting sent to the functions properly and the program keeps crashing.
Could you help identify where I am going wrong of if there is something I am missing? I don't need exact code for answers, just some guidance. Here is the code:
#define SIZE 3
struct Employee {
string firstName[SIZE];
string lastName[SIZE];
int id[SIZE];
int hoursWorked[SIZE];
int payRate[SIZE];
int stat[SIZE];
};
//Functions
int menu();
void printReport(Employee & employees);
void search(Employee & employees);
void calculatePay(Employee & employees);
void orderByLastName(Employee & employees);
void orderByid(Employee & employees);
void printActive(Employee & employees);
void printInactive(Employee & employees);
//Display Main Menu
int menu()
{
int choice;
cout << "1. Print out Employee Report. " << endl;
cout << "2. Search Employee Records. " << endl;
cout << "3. Display the Report in Sorted order on Last Name or ID. << endl;
cout << "4. Calculate Pay. " << endl;
cout << "5. Display Active Employees." << endl;
cout << "6. Display Inactive Employees." << endl;
cout << "7. Quit" << endl;
cout << "Enter your choice. ";
cin >> choice;
return choice;
}
//Display the employee data in a formatted order
void printReport(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] << endl;
}
//Search for employee ID
//Show "Not Found" if unable to locate
void search(Employee & employees)
{
bool found = false;
int idNumber;
int pos = -1;
cout << "Enter id number ";
cin >> idNumber;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.id[index] == idNumber)
{
found = true;
pos = index;
}
}
if (!found)
cout << "Not Found. " << endl;
else
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
//Calculate total weekly pay
void calculatePay(Employee & employees)
{
cout << setw(10) << "First Name" <<
setw(10) << "Last Name" <<
setw(10) << "ID" <<
setw(10) << "Hours" <<
setw(10) << "Rate" <<
setw(10) << "Total Pay" <<
endl;
ios::fixed;
for (int index = 0; index < SIZE; index++)
cout << setw(10) << employees.firstName[index] <<
setw(10) << employees.lastName[index] <<
setw(10) << employees.id[index] <<
setw(10) << employees.hoursWorked[index] <<
setw(10) << employees.payRate[index] <<
setw(10) << employees.hoursWorked[index] * employees.payRate[index] << endl;
}
//Sort employee data by last name
void orderByLastName(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.lastName[j] > employees.lastName[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
//Sort employee data by ID
void orderByid(Employee & employees)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (employees.id[j] > employees.id[j + 1])
{
string temp = employees.lastName[j];
employees.lastName[j] = employees.lastName[j + 1];
employees.lastName[j + 1] = temp;
temp = employees.firstName[j];
employees.firstName[j] = employees.firstName[j + 1];
employees.firstName[j + 1] = temp;
int tempid = employees.id[j];
employees.id[j] = employees.id[j + 1];
employees.id[j + 1] = tempid;
int temphours = employees.hoursWorked[j];
employees.hoursWorked[j] = employees.hoursWorked[j + 1];
employees.hoursWorked[j + 1] = temphours;
int temppayrate = employees.payRate[j];
employees.payRate[j] = employees.payRate[j + 1];
employees.payRate[j + 1] = temppayrate;
}
}
}
}
void printActive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 1)
{
found = true;
pos = index;
}
if (!found) {
cout << "No active employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
void printInactive(Employee & employees)
{
bool found = false;
int pos = -1;
for (int index = 0; index < SIZE && !found; index++)
{
if (employees.stat[index] == 0)
{
found = true;
pos = index;
}
if (!found) {
cout << "No inactive employees." << endl;
}
else {
cout << setw(10) << employees.firstName[pos] <<
setw(10) << employees.lastName[pos] <<
setw(10) << employees.id[pos] <<
setw(10) << employees.hoursWorked[pos] <<
setw(10) << employees.payRate[pos] << endl;
}
}
}
int main()
{
struct Employee employees[SIZE];
//Read first and last name from user
for (int index = 0; index < SIZE; index++)
{
cout << "Enter first name : ";
cin >> employees[index].firstName[index];
cout << "Enter last name : ";
cin >> employees[index].lastName[index];
//Read ID, hours, and pay rate from user
while (employees[index].id[index] < 0)
{
cout << "Enter id : ";
cin >> employees[index].id[index];
if (employees[index].id[index] < 0)
{
cout << "Invalid Id number. " << endl;
cout << "Enter id : ";
cin >> employees[index].id[index];
}
}
while (employees[index].hoursWorked[index] < 0)
{
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
if (employees[index].hoursWorked[index] < 0)
{
cout << "Invalid hours. " << endl;
cout << "Enter hours worked : ";
cin >> employees[index].hoursWorked[index];
}
}
while (employees[index].payRate[index] < 0)
{
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
if (employees[index].payRate[index] < 0)
{
cout << "Invalid pay rate. " << endl;
cout << "Enter Pay Rate : ";
cin >> employees[index].payRate[index];
}
}
while (employees[index].stat[index] < 0)
{
cout << "Enter your status. (0 - Inactive, 1 - Active) : ";
cin >> employees[index].stat[index];
if (employees[index].stat[index] < 0)
{
cout << "Enter your status : ";
cin >> employees[index].stat[index];
}
cout << endl;
}
}
//Loop to display menu options until user quits program
while (true)
{
//Call menu with options
int ch = menu();
//Different options to choose
switch (ch)
{
case 1:
printReport(employees[SIZE]);
break;
case 2:
search(employees[SIZE]);
break;
case 3:
int sortType;
cout << "1.Sort by Last Name." << endl;
cout << "2.Sort by ID." << endl;
cout << "Enter your choice. ";
cin >> sortType;
if (sortType == 1)
orderByLastName(employees[SIZE]);
else if (sortType ==2)
orderByid(employees[SIZE]);
break;
case 4:
calculatePay(employees[SIZE]);
break;
case 5: printActive(employees[SIZE]);
case 6: printInactive(employees[SIZE]);
break;
case 7:
exit(0);
}
}
system("pause");
return 0;
}
Thank you in advance!
I ran your program, and I received more than 20 errors before the compiler involuntarily stopped trying to compile any longer. All of them are connected to the lines of code using cout, cin, string, and setw. You need to use these keywords with the std namespace to fix this, and you need to include the iostream header file (#include <iostream>). Either you can write std:: in front of all of these keywords (i.e. std::cout) or you can declare the namespace in the preprocessor (using namespace std;). Also, for std::setw, you need to include the iomanip header file (#include <iomanip>). After that, you're missing a quotation in the menu function and a bracket at the end of the main function. (There's also a couple of problems with initializing the size of the struct members in the declaration, but I'll leave that up to you.) Hope this helped!
Related
Good day, I'm having difficulty on the last two parts of my program where it's supposed to only output players who got maximum/minimum scores, I need help on how to do it because I'm really confused. If it's also alright to provide some explanations I'd really appreciate it.
I tried this approach:
#include <iostream>
using namespace std;
int main() {
double lrgst, lrgst2, lrgst3;
int numbers[5];
lrgst = lrgst2 = lrgst3;
for (int i = 0; i < 5; i++) {
cin >> numbers[i];
}
for (int i = 0; i < 5; i++) {
if (numbers[i] > lrgst) {
lrgst3 = lrgst2;
lrgst2 = lrgst;
lrgst = numbers[i];
} else if (numbers[i] > lrgst2) {
lrgst3 = lrgst2;
lrgst2 = numbers[i];
} else if (numbers[i] > lrgst3) {
lrgst3 = numbers[i];
}
}
cout << "largest are: " << lrgst << " " << lrgst2 << " " << lrgst3;
}
this is my actual code:
#include <iostream>
using namespace std;
struct playerdata {
char name[50];
int age, score1, score2;
double average;
};
int main() {
int choice, i = 1, j = 1, z = 1, backtomain2;
char backtomain;
playerdata p1[10];
do {
for (int a = 0; a < 47; a++) {
cout << "=";
}
cout << "\n";
for (int b = 0; b < 22; b++) {
cout << " ";
if (b == 21) {
cout << "MENU \n";
}
}
for (int c = 0; c < 47; c++) {
ocut << "=";
}
cout << " "
"\n1. Add record\n"
"2. View players records\n"
"3. Compute for the average\n"
"4. Show the player(s) who gets the max average.\n"
"5. Show the player(s) who gets the min average.\n"
"6. Exit\n"
"Enter your choice:";
cin >> choice;
if (choice == 1) {
cout << "Add player data" << endl;
do {
cout << "Enter player " << i << " nickname:";
cin >> p1[i].name;
cout << "Enter player " << i << " age:";
cin >> p1[i].age;
cout << "Enter player " << i << " score 1:";
cin >> p1[i].score1;
cout << "Enter player " << i << " score 2:";
cin >> p1[i].score2;
cout << "Enter again? (Y/N)";
cin >> backtomain;
i++;
}
while (backtomain != 'N' && backtomain != 'n' && i < 7);
if (choice == 2) {
cout << "Player records" << endl;
cout << "Player nickname "
<< "Player age "
<< " player score 1"
<< "
player score 2\n ";
for (z = 1; z <= i - 1; z++) {
cout << p1[z].name << " " << p1[z].age << "" << p1[z].score1 << ""
<< p1[z].score2 << "\n";
}
cout << "Press 1 to go back to main menu\n";
cin >> backtomain;
}
if (choice == 3) {
cout << "Computing for average...\n";
for (int d = 1; d <= i - 1; d++) {
p1[d].average = (p1[d].score1 + p1[d].score2) / 2.0;
cout << "\n" << p1[d].average << "\n";
}
cout << "Press 1 to go back to main menu\n";
cin >> backtomain;
}
if (choice == 4) {
cout << "Player(s) who got the max average:\n";
cout << "\nPress 1 to go back to main menu";
cin >> backtomain;
}
if (choice == 5) {
cout << "player(s) who got the min average: \n";
cout << "Press 1 to go back to main menu";
cin >> backtomain;
}
}
while (choice != 6);
}
You can simply sort the array of players for that
int n = sizeof(p1)/ sizeof(p1[0]);
sort(p1, p1+n, compPlayer);
//larget at pl[0]
//smallest at pl[9]
where
bool compPlayer(playerdata p1, playerdata p2) {
return (p1.score1+p1.score2) > (p2.score1+p2.score2);
//use score incase average has not been calculated for all players yet
}
I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});
I am working with a dynamic declaration of a 3 dimensional array of type CString. (I know, why CString again? Use vectors! I can't, the assignment requires use of cstring.)
So the assignment is to make a user defined playlist of songs which allows adding, removing, displaying, and searching. Also, the playlist must save to a text file called songs.txt.
My problem is I keep getting memory leaks in my adding function I will share all code and memory leak errors, so you can see.
Valgrind Errors:
==17401== HEAP SUMMARY:
==17401== in use at exit: 73,519 bytes in 31 blocks
==17401== total heap usage: 36 allocs, 5 frees, 91,199 bytes allocated
==17401==
==17401== 1 bytes in 1 blocks are definitely lost in loss record 1 of 12
==17401== at 0x4C284B7: operator new[](unsigned long) (in
/usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==17401== by 0x401BB3: songlist::readList(std::basic_ifstream<char,
std::char_traits<char> >&)
The rest just kind of repeats itself through 12 of 12
My code:
defs.cpp:
#includes <iostream>
#include <cstring>
#include <iomanip>
#include <fstream>
#include "proj4.h"
using namespace std;
void songlist::makeList()
{
MAX_TRAX = 0;
song = new char**[20];
for (int i=0; i<20; i++)
{
song[i] = new char*[5];
}
}
void songlist::readList(ifstream& infile)
{
int counter = 0;
if (!infile.is_open())
{
cout << "Cannot open file: songs.txt";
}
while(!infile.eof())
{
infile >> newSong.title >> newSong.artist >>
newSong.durationMin >> newSong.durationSec >> newSong.album;
int i = strlen(newSong.title);
i++;
int j = strlen(newSong.artist);
j++;
int k = strlen(newSong.durationMin);
k++;
int l = strlen(newSong.durationSec);
l++;
int m = strlen(newSong.album);
m++;
if(i>0)
{
song[counter][0]= new char[i];
song[counter][1]= new char[j];
song[counter][2]= new char[k];
song[counter][3]= new char[l];
song[counter][4]= new char[m];
song[counter][0] = newSong.title;
song[counter][1] = newSong.artist;
song[counter][2] = newSong.durationMin;
song[counter][3] = newSong.durationSec;
song[counter][4] = newSong.album;
counter++;
}
MAX_TRAX = counter-1;
}
counter = 0;
}
void songlist::saveList(ofstream& outfile)
{
if (!outfile.is_open())
{
cout << "Cannot find file: songs.txt";
}
for (int i=0; i<=MAX_TRAX; i++)
{
outfile << song[i][0] << "; " << song[i][1] << "; " << song[i]
[2] << "; " <<song[i][3] << "; " << song[i][4] << ";" << endl;
}
}
void songlist::displayList()const
{
cout << left << setw(16) << '#' << left << setw(30) << "Song Name" <<
left << setw(22) << "Artist Name" << left << setw(17) << "Duration" <<
left << setw(20) << "Album Title" << endl;
cout << left << setw(110) << setfill ('-') << '-' << endl;
cout << setfill (' ');
if (strlen(newSong.title)>=1)
{
for (int i=0; i<=MAX_TRAX; i++)
{
cout << left << setw(4) << i+1 << left << setw(31) <<
song[i][0] << left << setw(31) << song[i][1] << right << setw(4) << song[i]
[2]
<< ':';
if (strlen(song[i][3])==1)
{
cout << '0';
cout << left << setw(3) << song[i][3] <<
left << setw(3) << song[i][4] << endl;
}
else
cout << left << setw(4) << song[i][3] << left <<
setw(3) << song[i][4] << endl;
}
cout << left << setw(110) << setfill ('-') << '-' << endl;
cout << setfill (' ');
}
}
void songlist::addSong()
{
if(strlen(newSong.title)>=1)
{
MAX_TRAX++;
}
cout << "Add a Song" << endl;
cout << endl;
cout << "Enter Song Title: ";
cin.ignore();
cin.get(newSong.title, 30);
cout << endl;
cout << "Enter Artist Name: ";
cin.ignore();
cin.get(newSong.artist, 30);
cout << endl;
cout << "Enter Track Duration";
cout << endl;
cout << "Minutes: ";
cin.ignore();
cin.get(newSong.durationMin, 3);
cout << endl;
cout << "Seconds: ";
cin.ignore();
cin.get(newSong.durationSec, 3);
cout << endl;
cout << "Enter Album Title: ";
cin.ignore();
cin.get(newSong.album, 30);
cout << endl;
cout << "Song Added to Database!";
cout << endl;
cout << endl;
int i = strlen(newSong.title);
i++;
int j = strlen(newSong.artist);
j++;
int k = strlen(newSong.durationMin);
k++;
int l = strlen(newSong.durationSec);
l++;
int m = strlen(newSong.album);
m++;
song[MAX_TRAX][0]= new char[i];
song[MAX_TRAX][1]= new char[j];
song[MAX_TRAX][2]= new char[k];
song[MAX_TRAX][3]= new char[l];
song[MAX_TRAX][4]= new char[m];
song[MAX_TRAX][0] = newSong.title;
song[MAX_TRAX][1] = newSong.artist;
song[MAX_TRAX][2] = newSong.durationMin;
song[MAX_TRAX][3] = newSong.durationSec;
song[MAX_TRAX][4] = newSong.album;
}
void songlist::removeSong()
{
int p = 0;
int q = 0;
int n = 0;
cout << "Remove a Song" << endl;
cout << "Enter Track Number to Confirm Deletion: ";
cin >> n;
cout << endl;
while (!(n >=1 && n <= MAX_TRAX+1))
{
cin.clear();
cin.ignore();
cout << "Must be a number between 1 and " << MAX_TRAX+1 << endl;
cout << "Enter Track Number to Confirm Deletion: ";
cin >> n;
cout << endl;
}
n--;
for (p=n;p<MAX_TRAX; p++)
{
for(q=0;q<5;q++)
{
delete[] song[p][q];
}
int i = strlen(song[p+1][0]);
i++;
int j = strlen(song[p+1][1]);
j++;
int k = strlen(song[p+1][2]);
k++;
int l = strlen(song[p+1][3]);
l++;
int m = strlen(song[p+1][4]);
m++;
song[p][0] = new char[i];
song[p][1] = new char[j];
song[p][2] = new char[k];
song[p][3] = new char[l];
song[p][4] = new char[m];
song[p][0] = song[p+1][0];
song[p][1] = song[p+1][0];
song[p][2] = song[p+1][0];
song[p][3] = song[p+1][0];
song[p][4] = song[p+1][0];
}
MAX_TRAX--;
n++;
cout << "Track Number " << n << " Deleted" << endl;
}
void songlist::searchList()const
{
int i;
char aOrB;
int counter = 0;
char art[30];
char alb[30];
cout << "Search by (a)rtist or al(b)um? (a or b): ";
cin >> aOrB;
cout << endl;
if (aOrB != 'a' && aOrB != 'b')
{
cout << "(a or b): ";
cin >> aOrB;
cout << endl;
}
if (aOrB == 'a')
{
cout << "Artist Name: ";
cin.ignore();
cin.get(art, 30);
for(i=0; i<=(MAX_TRAX); i++)
{
if (strcmp(art, song[i][1])==0)
{
cout << left << setw(2) << i+1 << left <<
setw(32) << song[i][0] << left << setw(32) << song[i][1] << right << setw(4)
<< song[i][2] << ':' << left << setw(5) << song[i][3] << left << setw(32) <<
song[i][4] << endl;
counter++;
}
}
}
else
{
cout << "Album Name: ";
cin.ignore();
cin.get(alb, 30);
for(i=0; i<=(MAX_TRAX); i++)
{
if (strcmp(alb, song[i][4])==0)
{
cout << left << setw(2) << i+1 << left <<
setw(32) << song[i][0] << left << setw(32) << song[i][1] << right << setw(4)
<<
song[i][2] << ':' << left << setw(5) << song[i][3] << left << setw(32) <<
song[i][4] << endl;
counter++;
}
}
}
if (!counter)
{
cout << endl;
cout << "No Matches Found; check spelling and/or case." << endl;
}
}
void songlist::deleteAll()
{
for(int i=0; i>=20; i++)
{
for (int j=0; j<5; j++)
delete[] song[i][j];
delete[] song[i];
}
delete[] song;
}
songlist::songlist()
{
}
Proj4.h:
#ifndef PROJ3_H
#define PROJ3_H
#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
using namespace std;
class songlist
{
public:
void readList(ifstream& infile);
void saveList(ofstream& outfile);
void displayList() const;
void makeList();
void addSong();
void removeSong();
void searchList() const;
void deleteAll();
songlist();
private:
struct songs
{
char title[30] = {'\0'};
char artist[30] = {'\0'};
int intMin = 0;
int intSec = 0;
char durationMin[3] = {'\0'};
char durationSec[3] = {'\0'};
char album[30] = {'\0'};
};
songs newSong;
int MAX_TRAX;
char *** song;
};
#endif
app.cpp:
#include <iostream>
#include <cstring>
#include <iomanip>
#include <fstream>
#include "proj4.h"
using namespace std;
int main()
{
char selection;
cout << endl;
cout << "*Music Track Database*" << endl;
ifstream infile;
ofstream outfile;
infile.open("songs.txt");
outfile.open("songs.txt");
songlist newlist;
newlist.makeList();
do
{
cout << endl;
cout << "Main Menu:" << endl;
cout << endl;
cout << "(a)dd a song" << endl;
cout << "(r)emove a song" << endl;
cout << "(d)isplay track listings" << endl;
cout << "(s)earch for a track" << endl;
cout << "(q)uit" << endl;
cout << endl;
cout << "Select (a, r, d, s, q): ";
cin >> selection;
cout << endl;
if (selection != 'a' && selection != 'r' && selection != 'd'
&& selection != 's' && selection != 'q')
{
cout << "Select (a, r, d, s, q): ";
cin >> selection;
cout << endl;
}
switch (selection)
{
case 'a':
newlist.readList(infile);
newlist.addSong();
newlist.saveList(outfile);
break;
case 'd':
newlist.readList(infile);
newlist.displayList();
break;
case 'r':
newlist.removeSong();
newlist.saveList(outfile);
break;
case 's':
newlist.readList(infile);
newlist.searchList();
break;
}
}while (selection != 'q');
newlist.deleteAll();
cout << "Happy Trails To You; Until We Meet Again!" << endl;
cout << endl;
infile.close();
outfile.close();
return 0;
}
Also here is a simple makefile to test it:
all:
g++ app.cpp proj4.h defs.cpp -o proj4;
clean:
clean make;
Anything helps!
Thank You in advance.
You're not even allowed to use structs or classes? When you become a three star programmer it's usually very bad.
Your allocations are off by one (null termination...)
But the actual leak is here. Just think what this does:
song[p][0] = new char[i];
song[p][1] = new char[j];
song[p][2] = new char[k];
song[p][3] = new char[l];
song[p][4] = new char[m];
song[p][0] = song[p+1][0];
song[p][1] = song[p+1][0];
song[p][2] = song[p+1][0];
song[p][3] = song[p+1][0];
song[p][4] = song[p+1][0];
You first allocate memory and then throw the pointers away by assigning something else to those pointers. You can never get them back and that's a leak.
Instead of this:
song[counter][0] = new char[i];
song[counter][1] = new char[j];
song[counter][2] = new char[k];
song[counter][3] = new char[l];
song[counter][4] = new char[m];
song[counter][0] = newSong.title;
song[counter][1] = newSong.artist;
song[counter][2] = newSong.durationMin;
song[counter][3] = newSong.durationSec;
song[counter][4] = newSong.album;
Maybe Something more like:
song[counter][0] = new char[i];
song[counter][1] = new char[j];
song[counter][2] = new char[k];
song[counter][3] = new char[l];
song[counter][4] = new char[m];
strncpy(song[counter][0], newSong.title, i);
strncpy(song[counter][0], newSong.artist, j);
strncpy(song[counter][0], newSong.durationMin, k);
strncpy(song[counter][0], newSong.durationSec, l);
strncpy(song[counter][0], newSong.album, m);
This program seems to work fine until it goes to display the data after the sort function, it will display by destination but it bypasses displaying by airline. Then it gives the access violation window and I'm not 100% sure on what it even means. If anybody could explain and help that would be much appreciated.
#include <iostream>
#include <string>
using namespace std;
double flight_number[3], number_passengers[3], max_records, max_pass, min_pass;
string airline_name[3], destination[3], duplicate[3];
char reply, swapping;
int row, index[3];
void setup();
void load_arrays();
void display_airline();
void display_destination();
void sort();
int main()
{
setup();
load_arrays();
display_airline();
display_destination();
system("pause");
return 0;
}
void setup()
{
max_records = 3;
max_pass = 275;
min_pass = 50;
}
void load_arrays()
{
for (row = 0; row < max_records; row++)
{
cout << "Charter Number " << row << endl << endl;
cout << "Please enter..." << endl;
cout << "Airline Name----> ";
cin >> airline_name[row];
cout << endl;
cout << "Flight Number----> ";
cin >> flight_number[row];
cout << endl;
cout << "Destination----> ";
cin >> destination[row];
cout << endl;
cout << "Passenger Load----> ";
cin >> number_passengers[row];
cout << endl;
while (number_passengers[row] < min_pass || number_passengers[row] > max_pass)
{
cout << "You have entered an invalid amount of passengers." << endl;
cout << "There must be between 50 and 275 passengers. > ";
cin >> number_passengers[row];
cout << endl;
}
}
}
void display_airline()
{
system("cls");
for (row = 0; row < max_records; row++)
{
duplicate[row] = airline_name[row];
}
sort();
cout << "Airline" << " Flight" << " Destination" << " Passenger" << endl;
cout << "Name" << " Number" << " Load" << endl;
for (row = 0; row < max_records; row++)
{
cout << airline_name[index[row]] << " " << flight_number[index[row]] << " " << destination[index[row]] << " " << number_passengers[index[row]];
cout << endl;
}
}
void display_destination()
{
system("cls");
for (row = 0; row < max_records; row++)
{
duplicate[row] = destination[row];
}
sort();
cout << "Destination" << " Flight" << " Flight" << " Passenger" << endl;
cout << " Name" << " Number" << " Load" << endl;
for (row = 0; row < max_records; row++)
{
cout << destination[index[row]] << " " << airline_name[index[row]] << " " << flight_number[index[row]] << " " << number_passengers[index[row]];
cout << endl;
}
}
void sort()
{
for (row = 0; row < max_records; row++)
{
index[row] = row;
}
swapping = 'Y';
while (swapping == 'Y')
{
swapping = 'N';
for (row = 0; row < max_records; row++)
{
if (duplicate[row] > duplicate[row + 1])
{
swap (duplicate[row], duplicate[row + 1]);
swap (index[row], index[row + 1]);
swapping = 'Y';
}
}
}
}
also this is the full violation error: Unhandled exception at 0x009984F6 in Program 6.exe: 0xC0000005: Access violation reading location 0x03947188.
for (row = 0; row < max_records; row++)
if (duplicate[row] > duplicate[row + 1]).
What's duplicate[row+1] when row==3? You want the sort to go to max_records-1 since it works on pairs of elements rather than individual elements.
So first time posting and real beginner so hope doing this right but really need help with this program.
Thanks guys for all the help, I have made some changes and those errors have gone away, but now I am getting these:
Error 5 error LNK2019: unresolved external symbol "void __cdecl searchID(struct StudentRecord *,int)" (?searchID##YAXPAUStudentRecord##H#Z) referenced in function _main
Error 6 error LNK2019: unresolved external symbol "void __cdecl sortRecordsByName(struct StudentRecord *,int)" (?sortRecordsByName##YAXPAUStudentRecord##H#Z) referenced in function _main
Error 7 error LNK2019: unresolved external symbol "void __cdecl getInformation(struct StudentRecord * const,int)" (?getInformation##YAXQAUStudentRecord##H#Z) referenced in function _main
Error 8 error LNK1120: 3 unresolved externals
Here is the revised code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
const int MAX_SIZE = 20;
struct Answers
{
char answer1;
char answer2;
char answer3;
char answer4;
char answer5;
};
struct StudentRecord
{
int ID;
char student_name[MAX_SIZE];
Answers answer;
double score;
double average;
char letter_grade;
};
void getInformation(StudentRecord student[], int&);
void enterKey(char[]);
void calculateAvgAndLetter(StudentRecord *student, int, char[]);
void sortRecordsByName(StudentRecord * student, int);
void displayResults(StudentRecord * student, int);
bool displayReport(StudentRecord * student, int);
void searchID(StudentRecord * student, int);
int main()
{
int search;
int ID = 0;
bool check = false;
char repeat = 'y';
const int MAX_STUDENTS = 10;
int number_of_students = 0;
char key[5];
do {
cout << "How many students: ";
cin >> number_of_students;
StudentRecord student[MAX_STUDENTS];
enterKey(key);
getInformation(student,number_of_students);
calculateAvgAndLetter(student, number_of_students, key);
sortRecordsByName(student, number_of_students);
displayResults(student, number_of_students);
cout << "Would you like to search for a student (y for yes and n for no)?: ";
cin >> search;
while (search != 'n' && search != 'y')
{
cout << "Wrong ID" << endl;
cout << "Would you like to search for another student (y for yes and n for no)?: ";
cin >> search;
}
if (search == 'y')
{
searchID(student, number_of_students);
check = true;
}
else
check = false;
while (check)
{
cout << "Would you like to search for another student (y for yes and n for no)?: ";
cin >> search;
while (search != 'n' && search != 'y')
{
cout << "Wrong ID" << endl;
cout << "Would you like to search for another student (y for yes and n for no)?: ";
cin >> search;
}
if (search == 'y')
{
searchID(student, number_of_students);
check = true;
}
else
check = false;
}
cout << "Would you like to process another group of students(y for yes and n for no)?: " << endl;
cin >> repeat;
} while (repeat == 'y');
return 0;
}
void enterKey(char key[5])
{
for (int i = 0; i < 6; i++) {
cout << "Please enter the answer to question " << i + 1 << ": ";
cin >> key[i]; }
}
void getInformation(StudentRecord *student[],int number_of_students)
{
int max_students;
char again;
int i = 0;
cout << "Would you like to enter student information? " << endl;
cin >> again;
if (again == 'Y' || again == 'y')
{
do
{
cout << "Please enter student " << i + 1 << " information:" << endl;
cout << "Please Enter Student Name Last name first with no spaces: " << endl;
cin >> student[i]->student_name;
cout << "Please Enter Student Id Number: " << endl;
cin >> student[i]->ID;
cout << "Please enter the student's answer to question 1: ";
cin >> student[i]->answer.answer1;
cout << "Please enter the student's answer to question 2: ";
cin >> student[i]->answer.answer2;
cout << "Please enter the student's answer to question 3: ";
cin >> student[i]->answer.answer3;
cout << "Please enter the student's answer to question 4: ";
cin >> student[i]->answer.answer4;
cout << "Please enter the student's answer to question 5: ";
cin >> student[i]->answer.answer5;
i++;
if (i < number_of_students) {
cout << "Would you like to enter student information? " << endl;
cin >> again;
}
else again='n';
}
while(again == 'y' || again == 'Y');
cout<<"Reports:"<<endl;
}
}
void sortByID(StudentRecord student[], int number_of_students)
{
bool swap = true;
int j = 0;
int temp;
while (swap)
{
swap = false;
j++;
for (int i = 0; i < number_of_students - j; i++)
{
if (student[i].ID > student[i + 1].ID)
{
temp = student[i].ID;
student[i].ID = student[i + 1].ID;
student[i + 1].ID = temp;
swap = true;
}
}
}
}
int LinearSearch(StudentRecord student[], int number_of_students, int ID, int first, int last)
{
int i = 0;
int position;
for (int i = 0; i < number_of_students; i++)
{
if (ID == student[i].ID) {
position = i; }
}
return position;
}
void SortRecordsByName(StudentRecord student[], int number_of_students)
{
bool swap = true;
int j = 0;
StudentRecord temp;
while (swap)
{
swap = false;
j++;
for (int i = 0; i < number_of_students - j; i++)
{
if (student[i].student_name > student[i + 1].student_name)
{
strcpy(temp.student_name,student[i].student_name);
strcpy(student[i].student_name,student[i + 1].student_name);
strcpy(student[i + 1].student_name,temp.student_name);
swap = true;
}
}
}
}
void calculateAvgAndLetter(StudentRecord student[], int number_of_students, char key[5])
{
int points1;
int points2;
int points3;
int points4;
int points5;
int i = 0;
int j = 0;
for (int i = 0; i < number_of_students; i++)
{
if (student[i].answer.answer1 == key[0])
points1 = 10;
else
points1 = 0;
if (student[i].answer.answer2 == key[1])
points2 = 10;
else
points2 = 0;
if (student[i].answer.answer3 == key[2])
points3 = 10;
else
points3=0;
if (student[i].answer.answer4 == key[3])
points4 = 10;
else
points4 = 0;
if (student[i].answer.answer5 == key[4])
points5 = 10;
else
points5 = 0;
student[i].score= points1 + points2 + points3 + points4 + points5;
student[i].average = student[i].score * 2 ;
if((student[i].average >= 90) && (student[i].average <= 100))
student[i].letter_grade='A';
else if ((student[i].average >= 80) &&(student[i].average <= 89))
student[i].letter_grade='B';
else if ((student[i].average >= 70) && (student[i].average <= 79))
student[i].letter_grade='C';
else if ((student[i].average >= 60) && (student[i].average <= 69))
student[i].letter_grade='D';
else if ((student[i].average >= 0) && (student[i].average <= 59))
student[i].letter_grade='F'; }
}
void displayResults(StudentRecord student[], int number_of_students)
{
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) << "Answers" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(50) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
cout << setw(3) << student[i].ID << setw(15) << student[i].student_name << setw(10) << student[i].answer.answer1 << student[i].answer.answer2 << student[i].answer.answer3 << student[i].answer.answer4
<< student[i].answer.answer5 << setw(9) << student[i].score << setw(10) << student[i].average << setw(13) << student[i].letter_grade << endl;
cout <<"\n\n\nStudents admitted to graduate program: \n" << endl;
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(40) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
{
if (student[i].letter_grade == 'A' || student[i].letter_grade == 'B') {
cout << setw(2) << student[i].ID << setw(12) << student[i].student_name << setw(10) << student[i].score
<< setw(10) << student[i].average << setw(10) << student[i].letter_grade << endl; }
}
cout <<"\n\n\nStudents with Conditional Admission to Graduate Program: \n" << endl;
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(40) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
{
if (student[i].letter_grade == 'C') {
cout << setw(2) << student[i].ID << setw(10) << student[i].student_name << setw(10) << student[i].score
<< setw(10) << student[i].average << setw(10) << student[i].letter_grade << endl; }
}
cout <<"\n\n\nStudents Not Allowed Admission: \n" << endl;
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(40) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
{
if (student[i].letter_grade == 'D' || student[i].letter_grade == 'F') {
cout << setw(2) << student[i].ID << setw(10) << student[i].student_name << setw(10) << student[i].score
<< setw(10) << student[i].average << setw(10) << student[i].letter_grade << endl; }
}
}
void searchIDandDisplay(StudentRecord student[], int number_of_students, int ID)
{
bool check = true;
string acceptence;
cout << "\n\n\nEnter the ID of the student: ";
cin >> ID;
while (check)
{
for(int i = 0; i < number_of_students; i++)
{
if (ID == student[i].ID)
{
check = false;
}
}
if (check == true)
{
cout << "No student with this ID" << endl;
cin >> ID;
}
}
int i = LinearSearch(student, number_of_students, ID, student[0].ID, student[number_of_students].ID);
if (student[i].letter_grade == 'A' || student[i].letter_grade == 'B' || student[i].letter_grade == 'C') {
acceptence = "Accepted"; }
else
acceptence = "Denied";
cout << fixed << setprecision(2);
cout << "Student ID" << setw(10)
<< "StudentName"
<< setw(10) << setw(10)
<<"Total Pts" << setw(10)
<< "Average" << setw(10)
<< "Letter Grade"
<< "Status" << endl;
cout << setfill('-');
cout << setw(48) << "-" << endl;
cout << setfill(' ');
cout << setw(2) << student[i].ID
<< setw(10) << student[i].student_name
<< setw(10) << student[i].score
<< setw(10) << student[i].average
<< setw(10) << student[i].letter_grade
<< setw(10) << acceptence <<endl;
}
Like I said a real beginner so any help will be greatly appreciated, and hope I posted right, sorry if anything wrong. And again thanks guys for any help!
void getInformation(StudentRecord *student[], int& num_std);
This says getInformation takes an array of pointers to StudentRecord. You want just
void getInformation(StudentRecord student[], int& num_std);
which takes an array of StudentRecords.
void getInformation(StudentRecord *student[], int& num_std);
In this declaration, student is taken as a pointer to pointer to StudentRecord. Change it to:
void getInformation(StudentRecord *student, int& num_std);
or
void getInformation(StudentRecord student[], int& num_std);
The problem is this line
getInformation(student,number_of_students);
The type of student here is a StudentRecord[] but the parameter of getInforamtion is typed to StudentRecord[]*. In order to make the types line up you need to change the type of the parameter to StudentRecord* or pass the address of student.
Given that you are passing the size along with the set of values I would favor changing the signature of getInformation to
void getInformation(StudentRecord *student, int& num_std);
Some comments
int search;
int ID = 0;
bool check = false;
char repeat = 'y';
const int MAX_STUDENTS = 5;
int number_of_students = 0;
char key[5];
do {
cout << "How many students: ";
cin >> number_of_students;
you should check if (number_of_students < MAX_STUDENTS) before continuing
your array key has dimension 5 but in your for loop you go from 0..5 which is six, better still give the dimension as an argument to the function enterKey(char *key, int maxsize) { ... }
void enterKey(char key[5]) -> (char* key, int maxsize)
{
for (int i = 0; i < 6; i++) -> for (int i=0; i<maxsize; ++i)
{
cout << "Please enter the answer to question " << i + 1 << ": ";
cin >> key[i];
}
}
the formal argument specifies an array of StudentRecord pointers
void getInformation(StudentRecord *student[],int number_of_students)
but you do not supply that in this way:
StudentRecord student[MAX_STUDENTS];
enterKey(key);
getInformation(student,number_of_students);
if you write as above then student is an array of StudentRecords
instead you should change the prototype to look like this (remember array decays to ptr):
void getInformation(StudentRecord *student,int number_of_students)
another tip
your struct Answers has 5 answer characters answer1,answer2,.. it would be more convenient to have it as an array, then you could shorten down the way you input the answers
Your prototypes don't need names for their arguments. They just need the data types.
void getInformation(StudentRecord*, int&);
void enterKey(char[]);
void calculateAvgAndLetter(StudentRecord*, int, char[]);
void sortRecordsByName(StudentRecord*, int);
void displayResults(StudentRecord*, int);
bool displayReport(StudentRecord*, int);
void searchID(StudentRecord*, int);
Your prototype for getInformation:
void getInformation(StudentRecord *student[], int& num_std);
has its second parameter typed as int&, whereas your definition:
void getInformation(StudentRecord *student[],int number_of_students)
is missing the &. In this case, you could either remove the & from the prototype or add it to the definition and your current implementation should work the same.
And as others have said, you're overstating the first parameter. Try Removing either the [] or the * (arrays are always passed by reference anyway).