0% found this document useful (0 votes)
50 views54 pages

Final Sig

The document contains code for a vehicle crash simulation program with the following functionality: 1. It defines a main function that initializes variables and calls functions to run the menu, validate user input, and close the vehicle file when exiting. 2. It includes headers and defines functions for menu display, user input validation, and reading from/writing to an external vehicle file to create, edit and view vehicle details. 3. The menu functions allow users to select scenarios, create/edit vehicles by providing details like name, mass, velocity etc. and view the vehicle list stored in an external file.

Uploaded by

api-690889230
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views54 pages

Final Sig

The document contains code for a vehicle crash simulation program with the following functionality: 1. It defines a main function that initializes variables and calls functions to run the menu, validate user input, and close the vehicle file when exiting. 2. It includes headers and defines functions for menu display, user input validation, and reading from/writing to an external vehicle file to create, edit and view vehicle details. 3. The menu functions allow users to select scenarios, create/edit vehicles by providing details like name, mass, velocity etc. and view the vehicle list stored in an external file.

Uploaded by

api-690889230
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

//===================================================

// MAIN.CPP

//===================================================

//Include libraries

#include "crash.h" //include crash.h headers

#include <iostream> //include input/output stream

#include <fstream> //include file-stream

using namespace std; //standard namespace formatting

int main() //main client

bool exitProgram = false; // exit program initalized to false

int userMenuChoice = 0; //default initalization of menuChoice to zero

fstream vehicleFile; //create a vehicle file stream container to read/write data

vehicleFile.open("vehicles.txt", ios::out | ios::in | ios::app); //open the file for output/input/appending

while (exitProgram != true) //while exitProgram is not equal to exit stay in program

recursiveInputValidation(&userMenuChoice); // input validation for menuChoice

menuChoiceSelect(userMenuChoice,&exitProgram,vehicleFile); //pass valid user menu choice, pointer


to exitProg and vehicle file by reference

// This point is reached only after exitProgram evaluates to true

vehicleFile.close(); //close the Fstream of vehicleFile.

return 0; //successfully reached end of program, return 0;


}

//===================================================

// CRASH.CPP

//===================================================

#include <iostream>

#include <iomanip>

#include <fstream>

#include <sstream>

#include <cmath>

#include "crash.h"

using namespace std;

//===================================================

// MENU /UI

//===================================================

//PRINT CAR GRAPHIC

void printWelcomeMenu()

cout << "\n\n";

cout << "\t┌─┐┌─┐┬─┐ ┌─┐┬─┐┌─┐┌─┐┬ ┬ ┌─┐┬┌┬┐┬ ┬┬ ┌─┐┌┬┐┌─┐┬─┐ " << endl;

cout << "\t│ ├─┤├┬┘ │ ├┬┘├─┤└─┐├─┤ └─┐│││││ ││ ├─┤ │ │ │├┬┘ " << endl;

cout << "\t└─┘┴ ┴┴└─ └─┘┴└─┴ ┴└─┘┴ ┴ └─┘┴┴ ┴└─┘┴─┘┴ ┴ ┴ └─┘┴└─ " << endl;

cout <<"\t ____----------- _____" << endl;

cout <<"\t|~~~~~~~~~~/~_--~~~------~~~~~ \\"<< endl;

cout << "\t`---`| _-~ | |"<< endl;

cout <<"\t _-~ <_ | |[]"<< endl;

cout <<"\t / ___ ~~--[""] | ________-------'_"<< endl;


cout <<"\t> /~` | |-. `|~~.~~~~~ _ ~ - _"<< endl;

cout <<"\t ~| |||% | | ~ ._ ~ _ ~ ._"<< endl;

cout << "\t `_//|_% | | ~ . ~-_ /|"<< endl;

cout <<"\t `--__ | _-____ /| ~-_ |/."<< endl;

cout <<"\t ~--_ / ,/ -~-_ | |/ _______---~/"<< endl;

cout <<"\t ~~-/._< | |`~~~~~~~~~~~~~ ##--~/"<< endl;

cout <<"\t | ) |`------##---~~~~-~ ) )"<< endl;

cout <<"\t ~-_/_/ ~~ ~~"<< endl;

void menubar()

cout << "\t=========================================================\n";

//PRINT MENU CHOICES

void menuSpace()

cout << "\t\t\t\t\t\t";

void printMenuChoices()

printWelcomeMenu();

cout << "\n\n\t=========================================================" << endl;

cout << "\t|\t\t\t\t\t\t MENU\t\t\t\t\t\t\t|" << endl;

cout << "\t=========================================================" << endl;

cout << "\t|\t1.\t\t\t\tScenario Select\t\t\t\t\t\t|" << endl;

cout << "\t---------------------------------------------------------" << endl;

cout << "\t|\t2.\t\t\t\tCreate Vehicles\t\t\t\t\t\t|" << endl;


cout << "\t---------------------------------------------------------" << endl;

cout << "\t|\t3.\t\t\t\tEdit Vehicles\t\t\t\t\t\t|" << endl;

cout << "\t---------------------------------------------------------" << endl;

cout << "\t|\t4.\t\t\t\tView Vehicle List\t\t\t\t\t|" << endl;

cout << "\t---------------------------------------------------------" << endl;

cout << "\t|\t5.\t\t\t\tExit Program\t\t\t\t\t\t|" << endl;

cout << "\t---------------------------------------------------------\n\n" << endl;

cout << ":";

void printVehicleEditMenu()

menubar();

menuSpace();

cout << "1. Name" << endl;

menuSpace();

cout << "2. Mass" << endl;

menuSpace();

cout << "3. Time" << endl;

menuSpace();

cout << "4. Velocity" << endl;

menuSpace();

cout << "5. Acceleration" << endl;

menuSpace();

cout << "6. Vehicle Type" << endl;

menuSpace();

cout << "7. Save & Exit" << endl;

menubar();

}
// TAKES USER INPUT AND RUNS THE MENU FUNCTION

void menuChoiceSelect(int choice,bool * exitProgram,fstream& vehicleFile)

switch(choice)

case 1://crash/scenario select

//cout << "Scenario Selection\n" << endl;

constructScenario(vehicleFile);

break;

case 2: //edit text file/vehicle

//cout << "\nCreate Vehicle" << endl;

editFile(vehicleFile);

break;

case 3://print all vehicle

//cout << "\n View Vehicle List" << endl;

editVehiclesInFile(vehicleFile);

break;

case 4:
{

readVehicleFile(vehicleFile);

break;

default: //default case, triggers boolean quit, leaves menu and ends program

menubar();

menuSpace();

cout << "Crash Ya Later!" << endl;

menubar();

*exitProgram = true;

break;

// USES RECUSRSION TO VALIDATE USER INPUT

void recursiveInputValidation(int * userMenuChoice)

printMenuChoices();// print menu

cin >> *userMenuChoice; // acquire user's menu choice

if((*userMenuChoice > 0) && (*userMenuChoice < 6)) // if choice is valid return choice

return;

}
else // else recurse until input IS valid

cout << "\n\n>>>>INVALID INPUT<<<<<\n\n" << endl;

recursiveInputValidation(userMenuChoice); //recursive function call

//===================================================

// File Functions

//===================================================

// VALIDATES IF FILE OPENED CORRECTLY

void ValidateFile(fstream& vehicleFile)

if(!vehicleFile) // if file is not open, print error.

cout << "Couldn't open file" << endl;

void resetFileValidate(fstream& vehicleFile)

vehicleFile.clear(); //CLEAR THE EOF BIT SET IF PREVIOUSLY TRIGGERED

vehicleFile.seekg(0);//SETS THE READ CURSOR TO THE BEGGINING OF FILE

ValidateFile(vehicleFile); // VALIDATE FILE

// EDIT THE FILE (VEHICLE CREATION)


void editFile(fstream& vehicleFile)

resetFileValidate(vehicleFile);

int userInput; // choice select for vehicle

cout << "What kind of vehicle do you want to create?" << endl;

cout << "1. Truck" << endl;

cout << "2. Coupe" << endl;

cout << "3. Bike" << endl;

cin >> userInput;

switch(userInput)

case 1:

Truck tempTruck; //create temporary truck

createVehicleForFile(vehicleFile, &tempTruck,userInput); //send truck to edit

break;

case 2:

Coupe tempCoupe; //create temporary coupe

createVehicleForFile(vehicleFile, &tempCoupe,userInput);//send coupe to edit

break;

case 3:

{
Bike tempBike; //create temporary bike

createVehicleForFile(vehicleFile, &tempBike,userInput); //send bike to edit

break;

default :

cout <<"If you see this error has occured!" << endl; //default case, should never be reached.

break;

// CREATE A VEHICLE OBJECT FROM FILE

void createVehicleForFile(fstream& vehicleFile,Vehicle * tempVehicle,int type)

resetFileValidate(vehicleFile); // reset and point to start of fstream

//create temp variables for vehicle

string name;

double mass;

double time;

double velocity;

double acceleration;

// Type is the user's vehicle type

if(type == 1)

cout << "Please name your Truck" << endl;

cin.ignore();
getline(cin,name);

else if (type == 2)

cout << "Please name your Coupe" << endl;

cin.ignore();

getline(cin,name);

else

cout << "Please name your Motorcycle" << endl;

cin.ignore();

getline(cin,name);

//This section the user is prompted to enter the details of their vehicle

cout << "Please enter the mass of " << name <<" (KG) : ";

cin >> mass;

tempVehicle->setName(&name);

cout << "Please enter the duration of crash(seconds) : ";

cin >> time;

tempVehicle->setTime(&time);

cout << "Please enter the default avg velocity of " << name <<" (m/s) : ";

cin >> velocity;


tempVehicle->setVelocity(&velocity);

cout << "Please enter the acceleration of " << name <<" (m/s^2) : ";

cin >> acceleration;

tempVehicle->setAcc(&acceleration);

tempVehicle->printStats();

vehicleFile << name << "," << type <<","<< mass<< "," << time << "," << velocity << "," << acceleration <<
",";

vehicleFile.sync(); //sync to update text file after saving.

cout << "\n\n" << name << " saved successfully to vehicle.txt\n\t\t Returning to menu....\n" << endl;

//OPEN THE VEHICLE FILE FOR READING

void readVehicleFile(fstream& vehicleFile)

resetFileValidate(vehicleFile);

string tempstr; // TEMP STRING TO HOLD DATA READ FROM VEHICLE FILE

int tempInt = 0,vCounter = 0,userVchoice = 0;//tempInt counter keeps track of vehicle's stat pointer.
vCounter keeps track of which vehicle #.

while(vehicleFile) // WHILE VEHICLE FILE IS NOT FINISHED BEING READ

getline(vehicleFile,tempstr,','); // GRAB LINE UNTIL ','

if(tempInt % 6 == 0 && tempstr != "") // int%6 == 0 indicates that every 6 iterations it should be a vehicle
name, thus vehicle name and it is not empty.

{
vCounter++;//update vehicle counter, happens every 6 iterations

cout << "\t=========================================================";

cout << "\n\t|\t\t\t\t\t\tVEHICLE #" << (vCounter) <<"\t\t\t\t\t\t|"<< endl;

cout << "\t=========================================================" << endl;

cout << "\n\t\t\t\t\t\tName : " << tempstr << endl;

tempInt++; //every iteration temp int goes up by one to indicate to move to the next stat

else if (tempInt % 6 == 1) // 1 indicates type

cout << "\t\t\t\t\t\tType : " << tempstr << endl;

tempInt++;

else if (tempInt % 6 == 2) //2 indicates mass

cout << "\t\t\t\t\t\tMass : " << tempstr << endl;

tempInt++;

else if (tempInt % 6 == 3) //3 indicates time

cout << "\t\t\t\t\t\tTime : " << tempstr << endl;

tempInt++;

else if (tempInt % 6 == 4) //4 indicates velocity

cout << "\t\t\t\t\t\tVelocity : " << tempstr << endl;

tempInt++;

}
else if (tempInt % 6 == 5)// indicates acceleration

cout << "\t\t\t\t\t\tAcceleration : " << tempstr << "\n" << endl;;

tempInt++;

else

//cout << "else case" << endl;

Vehicle returnVehicle(fstream& vehicleFile,int userChoice) //returns a vehicle CollisonCourse from text


file

resetFileValidate(vehicleFile);//reset the vehicle file and point to the start of fstream

string tempstr; //temporary string to hold the read string.

Vehicle tempV; //temporary vehicle to be edited and replaced with data from fstream

int tempInt = 0,vCounter = 0,statCounter = 0;

while(vehicleFile)// while not end of vehicleFile

getline(vehicleFile,tempstr,','); //get line with the delimiter being ','

++tempInt; //

if((tempInt - 1) % 6 == 0) //every 6 iterations tempint indicates the end of a vheicle

vCounter++; //+1 to vehicle count


}

if(userChoice == vCounter) // if the userChoice matches the vehicle number

if(statCounter == 0) //stat counter keeps track of which statistic to edit for vehicle

tempV.setName(&tempstr); // fill the tempVehicle name from fstream

statCounter++;

else if(statCounter == 1)

int tempI = stoi(tempstr); // set the type of vehicle from filestream by converting from string to int

tempV.setType(&tempI);

statCounter++;

else if (statCounter == 2)

double tempD = stod(tempstr);

tempV.setMass(&tempD);

statCounter++;

else if (statCounter == 3)

double tempD = stod(tempstr); // set time from string using string to double conversion

tempV.setTime(&tempD);

statCounter++;
}

else if (statCounter == 4)

double tempD = stod(tempstr);

tempV.setVelocity(&tempD); // set velocity from fstream using string to double conversion

statCounter++;

else if (statCounter == 5)

double tempD = stod(tempstr);

tempV.setAcc(&tempD); // set acceleration from fstream using string to double conversion

statCounter++;

return(tempV); //return the fleshed out vehicle

Vehicle textToVehicle(fstream& vehicleFile) //takes user's choice-> reads file-> creates vehicle obj and
returns the vehicle

int userVchoice; //user's vehicle choice selection

Vehicle tempVehicle; // default constructed vehicle that will be edited and returned.

resetFileValidate(vehicleFile); //reset fstream

readVehicleFile(vehicleFile); //print vehicle choices

menubar();
cout <<"\n";

menuSpace();

cout << "Choose your vehicle #" << endl; // prompt

cin >> userVchoice; //take in the user's choice

tempVehicle = returnVehicle(vehicleFile,userVchoice); //set default constructed vehicle to the returned


vehicle

tempVehicle.printStats(); // print picked vehicle's stats

return tempVehicle; //returns the full vehicle

///////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////VEHICLE EDITOR///////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////

void editVehiclesInFile(fstream& vehicleFile)

bool exitVehicleEdit = false;

Vehicle tempVehicle;

int vehiclePick,editPick;

string oldVehicleName;

readVehicleFile(vehicleFile);

cout << "\n\t ENTER VEHICLE #:";

cin >> vehiclePick;

tempVehicle = returnVehicle(vehicleFile,vehiclePick);

oldVehicleName = tempVehicle.getName();

tempVehicle.printStats();

while(exitVehicleEdit == false)

menubar();
menuSpace();

cout << "EDIT OPTIONS" << endl;

printVehicleEditMenu();

cin >> editPick;

switch(editPick)

case 1:

string newName;

cout << "Current name is :" << tempVehicle.getName() << endl;

cout << "Enter the new name :";

cin.ignore();

getline(cin,newName);

tempVehicle.setName(&newName);

tempVehicle.printStats();

break;

case 2:

double tempD;

cout << "Current mass is :" << tempVehicle.getMass() <<" KG"<< endl;

cout << "Enter the new mass :";

cin >> tempD;

tempVehicle.setMass(&tempD);

tempVehicle.printStats();

break;

}
case 3:

double tempD;

cout << "Current duration of crash is :" << tempVehicle.getTime() << "Seconds" << endl;

cout << "Enter the new duration of crash :";

cin >> tempD;

tempVehicle.setTime(&tempD);

tempVehicle.printStats();

break;

case 4:

double tempD;

cout << "Current velocity is :" << tempVehicle.getVelocity() << "m/s" << endl;

cout << "Enter the new velocity :";

cin >> tempD;

tempVehicle.setVelocity(&tempD);

tempVehicle.printStats();

break;

case 5:

double tempD;

cout << "Current acceleration is :" << tempVehicle.getAcc() << "m/s^2" << endl;

cin >> tempD;

cout << "Enter the new acceleration :";

tempVehicle.setAcc(&tempD);

tempVehicle.printStats();
break;

case 6:

int tempI;

do{

cout << "Current Type is :" << tempVehicle.getType() << endl;

cout << "Pick a new status for " << tempVehicle.getName() << endl;

cout << "0.Undefined Vehicle\n1. Truck\n2.Coupe\n3.Motorcycle" << endl;

cin >> tempI;

}while(tempI > 3 || tempI < 0);

tempVehicle.setType(&tempI);

tempVehicle.printStats();

break;

default:

saveEditedVehicleToFile(vehicleFile,&tempVehicle,&oldVehicleName);

menuSpace();

cout << "Saved! Returning to menu..." << endl;

menuSpace();

exitVehicleEdit = true;

break;

}
}

void saveEditedVehicleToFile(fstream& vehicleFile, Vehicle* recievedVehicle, string*


nameMatchVehicle)

resetFileValidate(vehicleFile);

int commaCounter;

string tempString;

//vehicleFile << name << "," << type <<","<< mass<< "," << time << "," << velocity << "," << acceleration
<< ",";

vehicleFile << recievedVehicle->getName() << "," << recievedVehicle->getType() << "," <<
recievedVehicle->getMass() << "," << recievedVehicle->getTime() << "," << recievedVehicle-
>getVelocity() << "," << recievedVehicle->getAcc() <<",";

//===================================================

// VEHICLE

//===================================================

Vehicle::Vehicle() // default vehicle constructor

name = "Default Vehicle";

mass = 0.0;

time = 0.0;

type = 0;
}

Vehicle::~Vehicle()

// cout << "Vehicle deconstructed" << endl;

/////////////////////GETTERS//////////////////////

string Vehicle::getName() {return name;} //returns Name on call

double Vehicle::getMass() {return mass;} //returns Mass on call

double Vehicle::getTime() {return time;} //returns Health on call

double Vehicle::getAcc() {return acceleration;} //returns Acceleration on call

double Vehicle::getVelocity() {return velocity;} //returns Velocity on call

int Vehicle::getType() {return type;} //returns Type on call

//////////////////////SETTERS/////////////////////

void Vehicle::setName(string * nameInput)

name = *(nameInput); //set vehicle's name to given variable's address

void Vehicle::setMass(double * massInput)

mass = *(massInput); //set vehicle's mass to given variable's address

void Vehicle::setAcc(double * accelerationInput)


{

acceleration = *(accelerationInput); //set vehicle's acceleration to given variable's address

void Vehicle::setTime(double * timeInput)

time = *(timeInput); //set vehicle's time to given variable's address

void Vehicle::setVelocity(double * velocityInput)

velocity = *(velocityInput); // set vehicle's velocity to given variable's address

void Vehicle::setType(int * typeInput)

type = *(typeInput); //set vehicle's type to given variable's address

////////////////////////PRINT VEHICLE STATS//////////////////////

// Print all of vehicle's stats//

void Vehicle::printStats()

cout <<"\n\n";

menubar();

cout << "\t|\t\t\t\t\t"<< name <<"'s Values\t\t\t\t\t|\n";

menubar();

cout <<"\n";
menuSpace();

cout << "Name : " << name << endl; //print name

menuSpace();

cout << "Mass : " << mass << " KG" << endl; //print mass

menuSpace();

cout << "Duration of Crash : " << time << " seconds" <<endl; //print time

menuSpace();

cout << "Velocity : " << velocity <<" m/s" << endl; //print velocity

menuSpace();

cout << "Acceleration : " << acceleration <<" m/s^2" << endl; //print accel

menuSpace();

//type indicates category of vehicle

if(type == 0)

cout << "Undefined Motor Vehicle" << endl;

else if (type == 1)

cout << "Type : Truck" << endl;

else if (type == 2)

cout << "Type : Coupe" << endl;

else if (type == 3)

{
cout <<"Type : Motorcycle" << endl;

else

cout << "Undefined Type" << endl;

cout << "\n\n";

//===================================================

// TRUCK

//===================================================

Truck::Truck() // constructor

name = "Average Truck";

mass = 2835.0; // mass in KiloGram

time = 0.0;

velocity = 0;

type = 1;

Truck::~Truck() // deconstructor

// cout << "Truck deconstructed" << endl;

}
//===================================================

// COUPE

//===================================================

Coupe::Coupe() // constructor

name = "Average Coupe";

mass = 1885.13; // mass in KiloGram

time = 0.0;

velocity = 0;

type = 2;

Coupe::~Coupe() // deconstructor

// cout << "Coupe deconstructed" << endl;

//===================================================

// BIKE

//===================================================

Bike::Bike() // constructor

name = "Average Motorcycle";

mass = 275.0; // mass in KiloGram

time = 0.0;

velocity = 0;

type = 3;
}

Bike::~Bike() // deconstructor

// cout << "Bike deconstructed" << endl;

//===================================================

// MAP

//===================================================

///////////////////////////SETTERS////////////////////////

void Map::setVehicle(Vehicle userV) //setting the first vehicle onto the map

v1 = userV;

void Map::setVehicle1(Vehicle userV2) //setting the seond vehicle onto the map

v2 = userV2;

void Map::setHumanMass(double humanM)//Setting human mass for vehicle #1

humanMass = humanM;

void Map::setHumanMass2(double humanM2) //set human mass for vehicle #2


{

humanMass2 = humanM2;

///////////////////////GETTERS///////////////////////////

double Map::getHumanMass2()

return humanMass2;

Vehicle Map::getVehicle()

return v1;

Vehicle Map::getVehicle1()

return v2;

double Map::getHumanMass()

return humanMass;

/////////////////////////MAP & COLLISION CALCULATIONS//////////////////

//////////////////////CAR VS CAR/////////////////////////////

void Map::headOnCollision(Vehicle vehicle1, Vehicle vehicle2)


{

double vehicle_1_Mass_KG, vehicle_2_Mass_KG, human_1_Mass_KG, human_2_Mass_KG,


time_1_Seconds, time_2_Seconds, vehicle_1_velocity_MetersPerSecond,
vehicle_2_velocity_MetersPerSecond;

vehicle_1_Mass_KG = vehicle1.getMass();//gets variables from the class Vehicle through the recieved
variables of class Map

vehicle_2_Mass_KG = vehicle2.getMass();

human_1_Mass_KG = getHumanMass();

humanMass2 = getHumanMass2();

time_1_Seconds = vehicle1.getTime();

time_2_Seconds = vehicle2.getTime();

vehicle_1_velocity_MetersPerSecond = vehicle1.getVelocity();

vehicle_2_velocity_MetersPerSecond = vehicle2.getVelocity();

cout << "\n\n";

menubar();

menuSpace();

cout << "\tRESULTS" << endl;

menubar();

cout << "\tForce applied between both cars: " << fixed << setprecision(3) <<
((vehicle_1_Mass_KG)*pow(vehicle_1_velocity_MetersPerSecond,2))/2*(.4) +
((vehicle_1_Mass_KG)*pow(vehicle_1_velocity_MetersPerSecond,2))/2*(.4) << " N";//Equation: Force
Appiled(Newtons) = mass*speed^2/2*stopping distance + mass*speed^2/2*stopping distance

cout <<"\n\tForce Applied to human in vehicle 1: " << fixed << setprecision(3) <<
((human_1_Mass_KG)*pow(vehicle_1_velocity_MetersPerSecond,2))/2*(.03) << " N" <<
endl;//Equation: Force Appiled(Newtons) = mass of human*speed^2/2*stopping distance
cout <<"\tForce Applied to human in vehicle 2: " << fixed << setprecision(3) <<
((humanMass2)*pow(vehicle_2_velocity_MetersPerSecond,2))/2*(.03) << " N" << endl;//Equation:
Force Appiled(Newtons) = mass of human*speed^2/2*stopping distance

menubar();

//////////////////////CAR VS WALL//////////////////////////////

void Map::wallCollision(Vehicle vehicle1)

double mass, humanMass, time, speed;

mass = vehicle1.getMass();//gets variables from the class Vehicle through the recieved variables of
class Map

humanMass = getHumanMass();

time = vehicle1.getTime();

speed = vehicle1.getVelocity();

cout << "\n\n";

menubar();

menuSpace();

cout << "\tRESULTS" << endl;

menubar();

cout <<"\n\tForce Applied to human: " << fixed << setprecision(3) <<
((humanMass)*pow(speed,2))/2*(.03)<< " N" << endl;//Equation: Force Appiled(Newtons) = mass of
human*speed^2/2*stopping distance

cout <<"\n\tForce Applied to Wall: " << fixed << setprecision(3) << -(mass*speed)/time << " N" <<
endl;//Force of Impulse = change of momentum/time

menubar();
}

//Access to the text file to gather data to manipulate in the calculation

void headOn(fstream &vehicleFile)

Vehicle vehicle1, vehicle2;

Map CollisonCourse;

double humanMass, humanMass2;

vehicle1 = textToVehicle(vehicleFile);//where fstream is needed to store data in class


Truck/Coupe/Bike

vehicle2 = textToVehicle(vehicleFile);

menubar();

cout << "\tMass Of Vehicle 1 Passenger? (kg): ";

cin >> humanMass;

cout << "\tMass Of Vehicle 2 Passenger? (kg): ";

cin >> humanMass2;

menubar();

CollisonCourse.setHumanMass(humanMass);

CollisonCourse.setHumanMass2(humanMass2);

CollisonCourse.headOnCollision(vehicle1, vehicle2);

//Access to the text file to gather data to manipulate in the calculation


void wall(fstream &vehicleFile)

double passengerMass;

Vehicle vehicle1;

Map CollisonCourse;

vehicle1 = textToVehicle(vehicleFile);//where fstream is needed to store data in class


Truck/Coupe/Bike

menubar();

cout << "\tWhat is the mass of the passanger?(KG):";

cin >> passengerMass;

CollisonCourse.setHumanMass(passengerMass);

CollisonCourse.wallCollision(vehicle1);

void constructScenario(fstream& VehicleFile)

int menuChoice;

menubar();

menuSpace();

cout << "1. Head on Collision" << endl;

menubar();

menuSpace();

cout << "2. Collision to wall\n";

menubar();

cout << ":";

cin >> menuChoice;


if (menuChoice == 1) //if the user chooses head on collision

headOn(VehicleFile);

else //if the user chooses Collision to Wall

wall(VehicleFile);

//////////////////////////////////////////HEADER////////////////////////////////////////////////

// define header guards for crash.h

#ifndef CRASH_HEADER

#define CRASH_HEADER

//#include headers

#include <iostream>

#include<fstream>

using namespace std;

//===================================================

// MENU /UI

//===================================================

void printWelcomeMenu(); //prints text car

void printMenuChoices(); //print menu choices


void recursiveInputValidation(int*); //recursively ask user's input until it is valid then send it to
menuChoiceSelect;

void menuChoiceSelect(int,bool*,fstream&); // take the user's menu input,status of program as pointer


to bool and file stream

void constructScenario(fstream&);

void editVehiclesInFile(fstream&);

void printVehicleEditMenu();

void menuBar();

void menuSpace();

//===================================================

// VEHICLE CLASS

//===================================================

class Vehicle //parent vehicle class

protected: // inheritable variables

int type; //dictates classification of vehicle type

string name; //name of the vehicle

double mass,time,velocity,acceleration; //physical & statistical descriptors

public:

Vehicle(); //constructor

~Vehicle(); //destructor

//SETTERS

void setTime(double*); //set the vehicles health to given value

void setName(string*); //set the vehicles name to given string

void setMass(double*); //set the vehicles mass to given double

void setAcc(double*); //set the vehicles acceleration to given double


void setVelocity(double*); //set the vehicles velocity to the given double

void printStats(); //print all stats of given vehicle

void setType(int*); //set the type of vehicle by given int

//GETTERS

string getName(); //return name

double getMass(); //return mass

double getTime(); //return time

double getVelocity(); //return velocity

double getAcc(); //return acceleration

int getType(); //return type of vehicle

//saveToFile

void saveVehicle(fstream&,Vehicle); //saves vehicle to file

};

//===================================================

// TRUCK CLASS

//===================================================

class Truck : public Vehicle //child class truck

public:

Truck();

~Truck();

};

//===================================================

// COUPE CLASS
//===================================================

class Coupe : public Vehicle //child coupe class

public:

Coupe();

~Coupe();

};

//===================================================

// BIKE CLASS

//===================================================

class Bike : public Vehicle //child bike class

public:

Bike();

~Bike();

};

//===================================================

// MAP

//===================================================

class Map

private:

Vehicle v1;
Vehicle v2;

double humanMass, humanMass2;

public:

//setters

void setHumanMass(double);

void setHumanMass2(double);

void setVehicle(Vehicle);

void setVehicle1(Vehicle);

//getters

double getHumanMass();

double getHumanMass2();

Vehicle getVehicle();

Vehicle getVehicle1();

void headOnCollision(Vehicle, Vehicle);

void printMap(fstream&);

void wallCollision(Vehicle);

};

void headOn(fstream&);

void wall(fstream&);

//===================================================

// File Functions
//===================================================

void resetFileValidate(fstream&); // resets fstream position to inital and resets eof bit

void ValidateFile(fstream&); //validates if file is open correctly

void editFile(fstream&); //opens file and prompts for vehicle type

void createVehicleForFile(fstream&,Vehicle*,int); // user creates a vehicle object and saves it to file.

void readVehicleFile(fstream&); //reads the vehicle file and prints

Vehicle textToVehicle(fstream&); //takes user's choice-> reads file-> creates vehicle obj and returns the
vehicle

void editVehicle(fstream&);

void saveEditedVehicleToFile(fstream&, Vehicle*,string*);

#endif

Rene Rodriguez, Hamza Awan, Isaac Bernal.

Mrs. Lara

Programming Fundamentals 3

2 December 2022

Analysis

In this project Mrs. Lara gave us the opportunity to create our own project. With a couple of

requisites. The following requisites were recursion, pointers, sorting, searching, and inheritance.

Our idea is a car crash simulator. The scenarios are tested with different speeds, objects, masses

and with dummies to find out the damage of the person inside. We created a program where it
would test different vehicles, with different speeds, that have different masses, with different

scenarios as head on collision with another vehicle or a wall.

The way that we developed this project was by splitting into different files of

Implementation, Specification and Client files. The Specification file consists of a parent class

Vehicle with protected variables mass, and variables of data type integer. Class Vehicle has a

public with a constructor, and destructor. This parent class Vehicle has three child classes of

Truck, Coupe, and Bike that all access the protected variables of Class Vehicle. The child class

each consists of public constructors and destructors. The Implementation File carries the

definitions of the functions from the publics of the class. This allows you to enter multiple data

into an array of Objects. The array must dynamically allocate enough space to hold information

as needed. The data is read from a file and use the Object Oriented. We also display inheritance,

and recursion at some point, with pointers for sorting.

The user would be able to even create his own vehicle with its own mass and velocity on

the track. The outcome of the program would vary depending on the user which he would choose

the vehicle and the impact being either another vehicle or a massive wall. After the user inputs

both his vehicle and the types of scenarios that are available the program will run the data and

input it into the different formulas that we must get the information about the crash the formulas

that we have stored are such as Kinetic Energy divided by the stopping distance, Force of

Impulse change of momentum divided by time.


Algorithm

● int main () Main client.

● bool exitProgram = false; Exit program initialize to false.

● int userMenuChoice = 0; Default initialization of menuChoice to zero.

● fstream vehicleFile; Create a vehicle file stream container to read/write data.


● vehicleFile.open("vehicles.txt", ios::out | ios::in | ios::app); Open the file for

output/input/appending.

● while (exitProgram != true) While exitProgram is not equal to exit stay in program.

● recursiveInputValidation(&userMenuChoice); Input validation for menuChoice.

● menuChoiceSelect(userMenuChoice,&exitProgram,vehicleFile); Pass valid user menu

choice, pointer to exitProg and vehicle file by reference.

● This point is reached only after exitProgram evaluates to true vehicleFile.close(); Close

the Fstream of vehicleFile.

● return 0; Successfully reached end of program, return 0;

Crash Header File

● void printWelcomeMenu(); Prints text car.

● void printMenuChoices(); Print menu choices.

● void recursiveInputValidation(int*); Recursively ask user's input until it is valid then

send it to menuChoiceSelect;

● void menuChoiceSelect(int,bool*,fstream&); Take the user's menu input, status of

program as pointer to bool and file stream.


Class Vehicle Returns

SETTERS

● void setTime(double*); Set the vehicles health to given value.

● void setName(string*); Set the vehicles name to given string.

● void setMass(double*); Set the vehicles mass to given double.

● void setAcc(double*); Set the vehicles acceleration to given double.

● void setVelocity(double*); Set the vehicles velocity to the given double.

● void printStats(); Print all stats of given vehicle.

● void setType(int*); Set the type of vehicle by given int.

GETTERS

● string getName(); Return name.

● double getMass(); Return mass.


● double getTime(); Return time.

● double getVelocity(); Return velocity.

● double getAcc(); Return acceleration.

● int getType(); Return type of vehicle.

● saveToFile void saveVehicle(fstream&, Vehicle); Saves vehicle to file.

File Functions

● void resetFileValidate(fstream&); Resets fstream position to initial and resets eof bit.

● void ValidateFile(fstream&); Validates if file is open correctly.

● void editFile(fstream&); Opens file and prompts for vehicle type.

● void createVehicleForFile(fstream&, Vehicle*,int); User creates a vehicle object and

saves it to file.

● void readVehicleFile(fstream&); Reads the vehicle file and prints.

● Vehicle textToVehicle(fstream&); Takes user's choice-> reads file-> creates vehicle obj

and returns the vehicle.


Crash.cpp

● void printVehicleEditMenu() This is where the name, mass, time, acceleration.

● Void menuChoiceSelect Is for the user to select the vehicle and scenario.

● Void recursiveInputValidation Is to get the recursion validation of user menu.

● Void validateFile Uses fstream uses case to perform the scenarios.

● Void createvehicleforfile Is technically the creation of the edited vehicle.

● Void readVehicleFile Is used to read the inputs given from the file.

● string tempstr; Hold data read from vehicle file

Collision Formulas

● Force applied between both cars.

(vehicle_1_Mass_KG) *pow(vehicle_1_velocity_MetersPerSecond,2))/2*(.4) +

((vehicle_1_Mass_KG) *pow(vehicle_1_velocity_MetersPerSecond,2))/2*(.4) << " N";


Equation: Force Applied (Newtons) = mass*speed^2/2*stopping distance +

mass*speed^2/2*stopping distance.

● Force applied to human in vehicle 1.

(human_1_Mass_KG) *pow(vehicle_1_velocity_MetersPerSecond,2))/2*(.03) << " N"

<< endl; Equation: Force Applied (Newtons) = mass of human*speed^2/2*stopping

distance.

● Force applied to human in vehicle 2.

(humanMass2)*pow(vehicle_2_velocity_MetersPerSecond,2))/2*(.03) << " N" << endl;

Equation: Force Appiled(Newtons) = mass of human*speed^2/2*stopping distance.

● Force applied to human

(humanMass)*pow(speed,2))/2*(.03) << " N" << endl;

Equation: Force Appiled(Newtons) = mass of human*speed^2/2*stopping distance.

● Force applied to wall

(mass*speed)/time << " N" << endl; Force of Impulse = change of momentum/time

● void headOn Access to the text file to gather data to manipulate in the calculation
● void wall (fstream &vehicleFile) Access to the text file to gather data to manipulate in the

calculation.

Void Map

● void Map::setVehicle(Vehicle userV) Setting the first vehicle onto the map

{v1 = userV;

● void Map::setVehicle1(Vehicle userV2) Setting the second vehicle onto the map

{v2 = userV2;

● void Map::setHumanMass(double humanM) Setting human mass for vehicle #1

{ humanMass = humanM;

● void Map::setHumanMass2(double humanM2) Set human mass for vehicle #2

{humanMass2 = humanM2;

● This point is reached only after exitProgram evaluates to true vehicleFile.close(); Close

the Fstream of vehicleFile.

● return 0; Successfully reached end of program, return 0;


Isaac Bernal

Professor Lara

COSC-2436

01 December 2022

Project Essay

INTRODUCTION

Important algorithms to use in a database type of program are searching and sorting. You

use searching “for an entry in a database” or to “trawl through a virtual space” (Zaveri. 2018).

You also may use sorting because it “can help to sort database information, customer data, and

financial reports“(Fiverr. 2021). No matter the type of search or sort algorithms being used in the

code, the end goal is that it “best matches the size and structure of the database to provide a user-

friendly experience” (Zaveri. 2018), and “beneficial to your business and the right ones to use

when performing certain tasks that may require sorting larger portions of data” (Fiverr. 2021). In

our project, we found it beneficial to use the searching algorithm to properly search the requested

vehicle to be used in formulas to find the force outputted.

EXPLANATIONS

According to GeeksforGeeks, “Searching Algorithms are designed to check for an

element or retrieve an element from any data structure where it is stored” (Geeks. 2021). Our

code uses the searching algorithm to search a text file, using the name of the vehicle to retrieve

the requested appropriate info of the vehicle. Since the data we are requesting is a smaller list

compared to other databases, the search algorithm we use is Linear Search. We understand
Binary Search is more efficient, however since the list is smaller, the need to sort, which is

required in Binary Search, isn’t needed nor worth the data processing. The text file separates the

data using camas to be visually easier to read which data is what and easier for the code to

always read after the camas. The data is stored by vehicle name, type, mass, duration of crash,

initial velocity, and acceleration. The way the user searches the desired car is they are given the

list of custom they imputed, and they type in the number associated with the car and the search

function “returnVehicle” will manually start at the beginning of the text file and assign the info

to the variable of type class.

CONCLUSION

In our project, we found it beneficial to use the searching algorithm to properly search the

requested vehicle to be used in formulas to find the force outputted. We used the searching

algorithm to make it user friendly, so the user doesn't have to manually input every answer every

time they run the program. The program will hold the info to be ready for the next run on the

program. As previously stated, the end goal is that it “best matches the size and structure of the

database to provide a user-friendly experience” (Zaveri. 2018).


Works Cited

Fiverr Team. “Sorting Algorithms: What Are They and How to Use Them.” Programming

& Tech. Fiverr Blog. 2021. https://blog.fiverr.com/post/sorting-algorithms-what-are-they-

and-how-to-use-them

Zaveri, Meet. “An intro to Algorithms: Searching and Sorting algorithms.” codeburst.

2018. https://codeburst.io/algorithms-i-searching-and-sorting-algorithms-56497dbaef20

Srivastava, Prashant. “Difference Between Searching and Sorting Algorithms.” Geeks for

Geeks. 2021. https://www.geeksforgeeks.org/difference-between-searching-and-sorting-

algorithms/

You might also like