Finding the max in an array of Data-Structures - c++

I have a text file of cars:
2014 Toyota Tacoma 115.12 1
2012 Honda CRV 85.10 0
2015 Ford Fusion 90.89 0
2013 GMC Yukon 110.43 0
2009 Dodge Neon 45.25 1
2011 Toyota Rav4 65.02 1
2012 Mazda CX5 86.75 1
2016 Subaru Outback 71.27 0
2015 Ford F150 190.83 1
2010 Toyota Corolla 50.36 1
I am trying to find the max which is the float but I am having trouble finding it as well as finding the rental cost of the cars. I have this so far but am still having trouble.
#include <iostream>
#include <fstream>
using namespace std;
struct car
{
int year;
char make[10];
char model[10];
float price;
int available;
} ;
void menu();
// Main Function
int main ()
{
// declare variables
int carAmount = 10;
int choice;
car carLib[carAmount];
char filename[10];
ifstream carInData;
float mostExpensive = 0;
int MostExpensiveIndex;
int count = 0;
int days;
int rentalCost = 0;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
menu();
carInData.open(filename);
cin >> choice;
if(carInData.is_open());
{
// read list of names into array
for(cout; count < carAmount; count++){
carInData >> carLib[count].year >> carLib[count].make >> carLib[count].model >> carLib[count].price >> carLib[count].available;
switch (choice){
case 1:
if(carLib[count].available == 1)
cout << " Available ";
else
cout << " Unavailable ";
cout << carLib[count].year << " " << carLib[count].make << " " << carLib[count].model << " " << carLib[count].price << " " << "\n";
break;
case 2:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> carLib[count].price;
rentalCost += days * count;
cout << " Rental Cost for " << days << " days is " << rentalCost;
break;
case 3:
MostExpensiveIndex = count;
for(size_t carIndex = 0; carIndex < count; ++carIndex){
if(carLib[carAmount].price <= mostExpensive) continue;
mostExpensive = carLib[carIndex].price;
MostExpensiveIndex = carIndex;
}
const car & carI = carLib[MostExpensiveIndex];
cout << " Most Expensive car is: " << MostExpensiveIndex << " " << carI.year << " " << carI.make << " " << carI.model << " " << carI.price << "\n";
break;
}
}
}
return 0;
}
void menu(){
cout << " 1 - Show Cars\n";
cout << " 2 - Rental Cost\n";
cout << " 3 - Most Expensive Car\n";
}
My output is displaying all my cars instead of the maximum one. This is the screenshot of the output

Replace:
if(carLib[carAmount].price <= mostExpensive) continue;
with
if(carLib[carIndex].price <= mostExpensive) continue;
Correct code is:
#include <iostream>
#include <fstream>
using namespace std;
struct car {
int year;
char make[10];
char model[10];
float price;
int available;
} ;
void menu();
// Main Function
int main ()
{
// declare variables
int carAmount = 10;
int choice;
car carLib[carAmount];
char filename[10];
ifstream carInData;
float mostExpensive = 0;
int MostExpensiveIndex;
int count = 0;
int days;
float rentalCost = 0;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
menu();
carInData.open(filename);
cin >> choice;
if (carInData.is_open()) {
// read list of names into array
for (; count < carAmount; count++) {
carInData >> carLib[count].year >> carLib[count].make >> carLib[count].model >> carLib[count].price >> carLib[count].available;
}
}
switch (choice) {
case 1:
for (int carIndex = 0; carIndex < carAmount; ++carIndex){
if (carLib[carIndex].available == 1)
cout << " Available ";
else
cout << " Unavailable ";
cout << carLib[carIndex].year << " " << carLib[carIndex].make << " " << carLib[carIndex].model << " " << carLib[carIndex].price << " " << "\n";
}
break;
case 2:
cout << " Enter car number and how many days " << "\n";
cin >> count;
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
rentalCost = days * carLib[count].price;
cout << " Rental Cost for " << days << " days is " << rentalCost << endl;
break;
case 3:
MostExpensiveIndex = 0;
for (size_t carIndex = 0; carIndex < carAmount; ++carIndex) {
if (carLib[carIndex].price <= mostExpensive) continue;
mostExpensive = carLib[carIndex].price;
MostExpensiveIndex = carIndex;
}
const car & carI = carLib[MostExpensiveIndex];
cout << " Most Expensive car is: " << MostExpensiveIndex << " " << carI.year << " " << carI.make << " " << carI.model << " " << carI.price << "\n";
break;
}
return 0;
}
void menu()
{
cout << " 1 - Show Cars\n";
cout << " 2 - Rental Cost\n";
cout << " 3 - Most Expensive Car\n";
}

Related

gotoxy prints wrong in c++

I am making a menu for a store with 4 options; add product, delete product, see table of created products and exit the program.
I finished the option to add products and exit, they both work fine.
Now I have to make the option to see the product table, supposedly I had already finished it but I noticed a problem ...
The first time I go in to see the product table, it prints it to me normally, like this.
enter image description here
But when I go to the menu and go back to the product table, it prints it like this.
enter image description here
Like I said, it only prints it right the first time I see it, then it prints it wrong.
Do you know how I can solve it?
This is the part of the code where I print the product table.
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
This is my complete code (maybe I have one or another library too many because I have been experimenting).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
Thank you very much in advance :)
The main reason for this problem is that after the size of the console changes, the position of the symbols you draw has also changed. At the same time, the line break determined by cout<<endl; also has a problem. For example, after the window becomes larger, the line length of the console becomes larger, but cout<<endl; is still the original line length.
However, there is no good solution. I suggest you directly set the console size and m=5, m=m+2.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 1400, 400, TRUE);
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 5;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 2;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
In addition, it is not recommended that you use cmd to make gui.

Number that is inputted is not the same as displayed by the code, using array in a struct, why?

I'm making a code where users can type in numbers that will be stored in an array which is inside a struct. However, sometimes, the value that I input is not the same as the one that is stored/display. This problem is not very consistent. For example, when I input 10, it could either be shown as: 6384644, 6382852, or actually 10. I am very confused for this, I've tried changing the array data type using int, long, and double, but to no avail.
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
int n,x,totalAge = 0,maxAge = 0,avgAge = 0,maxGoals = 0,bestPlayer = 0, oldest = 0;
cout << "Input the number of players: ";
cin >> n;
cout << "Input the number of games: ";
cin >> x;
struct players {
string name;
string currTeam;
int shirtn;
int age;
float height;
float weight;
int totalGoals;
long goals[];
};
players goals[x];
players playerList[n];
for (int i = 0; i < n; i++) {
cout << "Player " << (i+1) << endl;
cout << "Input player's name: ";
cin.ignore();
getline (cin, playerList[i].name);
cout << "Input player's current team: ";
getline (cin, playerList[i].currTeam);
cout << "Input player's shirt number: ";
cin >> playerList[i].shirtn;
cout << "Input player's age: ";
cin >> playerList[i].age;
cout << "Input player's height (m): ";
cin >> playerList[i].height;
cout << "Input player's weight (kg): ";
cin >> playerList[i].weight;
cout << endl;
for (int a = 0; a < x; a++) {
playerList[i].goals[a] = 0;
playerList[i].totalGoals = 0;
}
for (int a = 0; a < x; a++) {
cout << "Game " << (a+1) << "'s number of goals: ";
cin >> playerList[i].goals[a];
playerList[i].totalGoals += playerList[i].goals[a];
}
if (playerList[i].totalGoals > maxGoals) {
maxGoals = playerList[i].totalGoals;
bestPlayer = i;
}
if (playerList[i].age > maxAge) {
maxAge = playerList[i].age;
oldest = i;
}
totalAge += playerList[i].age;
cout << endl;
}
cout << endl;
for (int i = 0; i < n; i++) {
cout << playerList[i].name << endl;
cout << "--------------------" << endl;
cout << "Current team: " << playerList[i].currTeam << endl;
cout << "Shirt Number: " << playerList[i].shirtn << endl;
cout << "Age: " << playerList[i].age << endl;
cout << "Height: " << playerList[i].height << " m" << endl;
cout << "Weight: " << playerList[i].weight << " kg" << endl;
cout << endl;
for (int a = 0; a < x; a++) {
cout << "Game " << (a+1) << "'s number of goals: " << playerList[i].goals[a] << endl;
}
cout << endl << endl;
}
avgAge = totalAge / n;
cout << "Average age of players: " << avgAge << endl;
cout << "Oldest Player: " << playerList[oldest].name << " (" << maxAge << ") ";
cout << "Player who got the most goals: " << playerList[bestPlayer].name << ", shirt number: " << playerList[bestPlayer].shirtn << ". With total goals of: " << playerList[bestPlayer].totalGoals << endl;
}
Your code's corrected version would be this:
#include<string>
#include<iostream>
#include<vector> //for vector
using namespace std;
struct players {
string name;
string currTeam;
int shirtn;
int age;
float height;
float weight;
int totalGoals;
vector<long> goals; //used vector instead of array
};
int main () {
int N, X;
int totalAge = 0, maxAge = 0, avgAge = 0, maxGoals = 0, bestPlayer = 0, oldest = 0;
cout << "Input the number of players: ";
cin >> N;
cout << "Input the number of games: ";
cin >> X;
players player[X];
for (int i = 0; i < N; i++) {
cout << "Player " << (i+1) << endl;
cout << "Input player's name: ";
cin>>player[i].name;
cout << "Input player's current team: ";
cin>>player[i].currTeam;
cout << "Input player's shirt number: ";
cin >> player[i].shirtn;
cout << "Input player's age: ";
cin >> player[i].age;
cout << "Input player's height (m): ";
cin >> player[i].height;
cout << "Input player's weight (kg): ";
cin >> player[i].weight;
cout << endl;
player[i].totalGoals = 0;
for (int a = 0; a < X; a++) {
long G;
cout << "Game " << (a+1) << "'s number of goals: ";
cin >> G;
player[i].goals.push_back(G);
player[i].totalGoals += G;
}
if (player[i].totalGoals > maxGoals) {
maxGoals = player[i].totalGoals;
bestPlayer = i;
}
if (player[i].age > maxAge) {
maxAge = player[i].age;
oldest = i;
}
totalAge += player[i].age;
cout << endl;
}
cout << endl;
for (int i = 0; i < N; i++) {
cout << player[i].name << endl;
cout << "--------------------" << endl;
cout << "Current team: " << player[i].currTeam << endl;
cout << "Shirt Number: " << player[i].shirtn << endl;
cout << "Age: " << player[i].age << endl;
cout << "Height: " << player[i].height << " m" << endl;
cout << "Weight: " << player[i].weight << " kg" << endl;
cout << endl;
for (int a = 0; a < X; a++) {
cout << "Game " << (a+1) << "'s number of goals: " << player[i].goals[a] << endl;
}
cout << endl << endl;
}
avgAge = totalAge / N;
cout << "Average age of players: " << avgAge << endl;
cout << "Oldest Player: " << player[oldest].name << " (" << maxAge << ") ";
cout << "Player who got the most goals: " << player[bestPlayer].name << ", shirt number: " << player[bestPlayer].shirtn << ". With total goals of: " << player[bestPlayer].totalGoals << endl;
return 0;
}

C++ MDC Final - Sort Names in Records Alphabetically While in Array Struct of Type Char

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;
});

Problems finding out total sum using data structures and arrays

I have this code that has several funtions and am almost done, I just am having trouble finding the rental cost on my program.
My program reads a text file of cars and the rental cost as shown here:
2014 Toyota Tacoma 115.12 1
2012 Honda CRV 85.10 0
2015 Ford Fusion 90.89 0
2013 GMC Yukon 110.43 0
2009 Dodge Neon 45.25 1
2011 Toyota Rav4 65.02 1
2012 Mazda CX5 86.75 1
2016 Subaru Outback 71.27 0
2015 Ford F150 200.83 1
2010 Toyota Corolla 50.36 1
The float character is the price ( rental cost )
However I want the user to input the car number ( 1-10) choose how many days and output the rental cost. I am just having trouble how it would read the input of the car the user wants. This is my main code, but what I need is to tell if case 3 needs work.
#include <iostream>
#include <fstream>
using namespace std;
struct car {
int year;
char make[10];
char model[10];
float price;
int available;
} ;
void menu();
// Main Function
int main ()
{
// declare variables
int carAmount = 10;
int choice;
car carLib[carAmount];
char filename[10];
ifstream carInData;
float mostExpensive = 0;
int MostExpensiveIndex;
int count = 0;
int days;
int rentalCost = 0;
bool menu1 = false;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
// Start loop menu
while(menu1 = true){
menu();
carInData.open(filename);
cin >> choice;
if (carInData.is_open()) {
// read list of names into array
for (; count < carAmount; count++) {
carInData >> carLib[count].year >> carLib[count].make >> carLib[count].model >> carLib[count].price >> carLib[count].available;
}
}
switch (choice) {
// Case 1 closes menu
case 1:
return 0;
break;
// Case 2 displays if car is available if 1, unavailable if 0
case 2:
// itterate through car array
for(count = 0; count < carAmount; count++){
// Displays if car is available or not
if (carLib[count].available == 1)
cout << " Available ";
else
cout << " Unavailable ";
// Display Cars
cout << carLib[count].year << " " << carLib[count].make << " " << carLib[count].model << " " << carLib[count].price << " " << "\n";
}
break;
// Display only available cars
case 3:
// itterate through car array
for(count = 0; count < carAmount; count++){
// Displays only available cars
if (carLib[count].available == 1){
cout << " Available ";
// Display Cars
cout << carLib[count].year << " " << carLib[count].make << " " << carLib[count].model << " " << carLib[count].price << " " << "\n";
}
}
break;
// Calculates rental cost
case 4:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> carLib[count].price;
rentalCost += days*count;
cout << " Rental Cost for " << days << " days is " << rentalCost << "\n";
break;
// Finds most expensive car
case 5:
MostExpensiveIndex = count;
for (size_t carIndex = 0; carIndex < carAmount; ++carIndex) {
if (carLib[carIndex].price <= mostExpensive) continue;
mostExpensive = carLib[carIndex].price;
MostExpensiveIndex = carIndex;
}
const car & carI = carLib[MostExpensiveIndex];
cout << " Most Expensive car is: " << " " << carI.year << " " << carI.make << " " << carI.model << " " << carI.price << "\n";
break;
}
}
return 0;
}
void menu()
{
cout << " 1 - Exit program.\n";
cout << " 2 - Show Cars\n";
cout << " 3 - Show only available cars.\n";
cout << " 4 - Rental Cost\n";
cout << " 5 - Most Expensive Car\n";
}
Unless I'm misunderstanding something with how your code is suppose to work, I think case 3 works fine. HOWEVER, it's case 4 that you should be worried about
case 4:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> carLib[count].price; // WHY IS THE USER CHANGING THE PRICE?
rentalCost += days*count; // WHY IS THE PRICE "DAYS * (CAR ID #)"
cout << " Rental Cost for " << days << " days is " << rentalCost << "\n";
break;
You can see my comments there. I would change this to
case 4:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> count ;
// Note the decrement of 'count' by one, since you expect the user
// to enter a number 1-10
// Should probably include a check that the 'count' is valid
rentalCost += days*carLib[count-1].price;
cout << " Rental Cost for " << days << " days is " << rentalCost << "\n";
break;
Note that carLib increments from 0->9, but your user might think it counts from 1-10. It might help when you print option 2 (all car information) that you include the car ID number that you're expecting from the user.
Also a few more questions for you
You're storing the rental cost as an int (not sure if that's by design), so just remember that the days*price computation will get rounded.
The rentalCost is incrementing to be bigger and bigger, so I'm guessing the user is renting multiple cars?
You should maybe do a check as to whether the user can actually rent a car before increasing their rental cost.

How to put variables into an array

I am making a Basketball Scoreboard that can determine the winner of the game in each quarter and the the main game.
How can i store the values of my variables in an array?
I want to put the values of "Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne" in an array and also the values of "Q1teamTwo, Q2teamTwo, Q3teamTwo ,Q4teamTwo" or make them elements of an array.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Team1;
string Team2;
double OTscore1;
double OTscore2;
int Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne;
int Q1teamTwo, Q2teamTwo, Q3teamTwo ,Q4teamTwo;
int Q2TeamOneTotal, Q3TeamOneTotal, Q4TeamOneTotal;
int Q2TeamTwoTotal, Q3TeamTwoTotal, Q4TeamTwoTotal;
double teamOneScore[4];
double teamTwoScore[4];
int index;
double sumOne, sumTwo;
cout << "BASKETBALL SCOREBOARD:\n" << endl;
cout << "Enter Team 1 name: ";
getline (cin, Team1);
cout << "Enter Team 2 name: ";
getline (cin, Team2);
//FIRST QUARTER
cout << "\nQUARTER 1:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q1teamOne;
cout << "Team " << Team2 << " Score: ";
cin >> Q1teamTwo;
if (Q1teamOne > Q1teamTwo)
{
cout <<"****" << "Team " << Team1 << " is Leading.****\n\n";
}
else if (Q1teamOne < Q1teamTwo)
{
cout <<"****" << Team2 << " is Leading.****\n\n";
}
else if (Q1teamOne = Q1teamTwo)
{
cout <<"****We Have a Tie!!****\n\n";
}
//SECOND QUARTER
cout << "\nQUARTER 2:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q2teamOne;
Q2TeamOneTotal = Q1teamOne + Q2teamOne;
cout <<"Total Score: "<< Q2TeamOneTotal <<endl;;
cout << "Team " << Team2 << " Score: ";
cin >> Q2teamTwo;
Q2TeamTwoTotal = Q1teamTwo + Q2teamTwo;
cout <<"Total Score: " << Q2TeamTwoTotal;
if (Q2TeamOneTotal > Q2TeamTwoTotal)
{
cout <<"\n****" << Team1 << " is Leading.****\n\n";
}
else if (Q2TeamOneTotal < Q2TeamTwoTotal)
{
cout <<"\n****" << Team2 << " is Leading.****\n\n";
}
else if (Q2TeamOneTotal = Q2TeamTwoTotal)
{
cout <<"\n****We Have a Tie!!****\n\n";
}
//THIRD QUARTER
cout << "\nQUARTER 3:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q3teamOne;
Q3TeamOneTotal = Q1teamOne + Q2teamOne + Q3teamOne;
cout <<"Total Score: "<< Q3TeamOneTotal <<endl;;
cout << "Team " << Team2 << " Score: ";
cin >> Q3teamTwo;
Q3TeamTwoTotal = Q1teamTwo + Q2teamTwo + Q3teamTwo;
cout <<"Total Score: " << Q3TeamTwoTotal;
if (Q3TeamOneTotal > Q3TeamTwoTotal)
{
cout <<"\n****" << Team1 << " is Leading.****\n\n";
}
else if (Q3TeamOneTotal < Q3TeamTwoTotal)
{
cout <<"\n****" << Team2 << " is Leading.****\n\n";
}
else if (Q3TeamOneTotal = Q3TeamTwoTotal)
{
cout <<"\n****We Have a Tie!!****\n\n";
}
//FOURTH QUARTER
cout << "\nQUARTER 4:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q4teamOne;
Q4TeamOneTotal = Q1teamOne + Q2teamOne + Q3teamOne + Q4teamOne;
cout <<"Total Score: "<< Q4TeamOneTotal <<endl;
cout << "Team " << Team2 << " Score: ";
cin >> Q4teamTwo;
Q4TeamTwoTotal = Q1teamTwo + Q2teamTwo + Q3teamTwo + Q4teamTwo;
cout <<"Total Score: " << Q4TeamTwoTotal;
if (Q4TeamOneTotal > Q4TeamTwoTotal)
{
cout <<"\n****" << Team1 << " is Leading.****\n\n";
}
else if (Q4TeamOneTotal < Q4TeamTwoTotal)
{
cout <<"\n****" << Team2 << " is Leading.****\n\n";
}
else if (Q4TeamOneTotal = Q4TeamTwoTotal)
{
cout <<"\n****We Have a Tie!!****\n\n";
}
For example
#include <functional>
//...
std::reference_wrapper<int> teamOne[] = { Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne };
std::reference_wrapper<int> teamTwo[] = { Q1teamTwo, Q2teamTwo, Q3teamTwo ,Q4teamTwo };
Here is a demonstrative program
#include <iostream>
#include <functional>
int main()
{
int Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne;
std::reference_wrapper<int> teamOne[] =
{
Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne
};
int i = 0;
for ( auto &x : teamOne ) x.get() = i++;
for ( const auto &x : teamOne ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The program output is
0 1 2 3
Or if the link between the original values and the array is not need then you could write simply
double teamOneScore[] = { Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne };
Also you could use initializer list in the range based for statement without declaring any array. For example
for ( int x : { Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne } ) std::cout << x << ' ';
std::cout << std::endl;
what about:
teamOneScore[ 0 ] = Q1teamOne;
teamOneScore[ 1 ] = Q2teamOne;
teamOneScore[ 2 ] = Q3teamOne;
teamOneScore[ 3 ] = Q4teamOne;
teamTwoScore[ 0 ] = Q1teamTwo;
teamTwoScore[ 1 ] = Q2teamTwo;
teamTwoScore[ 2 ] = Q3teamTwo;
teamTwoScore[ 3 ] = Q4teamTwo;
But consider:
the arrays teamOneScore and teamTwoScore are arrays of double and your scores are int, so:
change the type of the arrays to be ints or
cast the assignment as: teamOneScore[ 0 ] = static_cast< double >( Q1teamOne );
Also, just for your information, this comparison is not correct:
else if (Q4TeamOneTotal = Q4TeamTwoTotal)
It should be:
else if (Q4TeamOneTotal == Q4TeamTwoTotal)
As a final note, you can use the arrays to store the scores from the cin and avoid the use of the Q1teamOne, ... vars.