Basically, i'm working on some coursework which requires me to create a flight booking system that allows for up to two stops e.g. London to Paris to Barcelona to Hamburg. I managed to create a version where 1 stop works e.g. London to Paris to Barcelona but i cannot get this one to work. I have included my code below, whenever i call this function and pass it any two airports, it does not output anything. I appreciate the code below is lengthy but a lot of it is repetitive. I've also probably gone about programming this question the completely wrong way. If you have any better ideas on how to approach this, please do share.
Many thanks.
void searchAllFlights(string origin, string destination)
{
ifstream checkNumOfLines("flights.txt");
int numOfLines = 0;
for(string line; getline(checkNumOfLines, line);){
numOfLines++;
}
int lengthOfLines[10] = {0,0,0,0,0,0,0,0,0,0};
checkNumOfLines.clear();
checkNumOfLines.seekg(0, ios::beg);
int index = 0;
for(string line; getline(checkNumOfLines, line);){
lengthOfLines[index] = line.length();
index++;
}
int filePointers[11] = {0, lengthOfLines[0], lengthOfLines[0] + lengthOfLines[1], lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2],
lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2] + lengthOfLines[3], lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2] +
lengthOfLines[3] + lengthOfLines[4], lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2] +
lengthOfLines[3] + lengthOfLines[4] + lengthOfLines[5], lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2] +
lengthOfLines[3] + lengthOfLines[4] + lengthOfLines[5] + lengthOfLines[6], lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2] +
lengthOfLines[3] + lengthOfLines[4] + lengthOfLines[5] + lengthOfLines[6] + lengthOfLines[7], lengthOfLines[0] + lengthOfLines[1]
+ lengthOfLines[2] + lengthOfLines[3] + lengthOfLines[4] + lengthOfLines[5] + lengthOfLines[6] + lengthOfLines[7] + lengthOfLines[8],
lengthOfLines[0] + lengthOfLines[1] + lengthOfLines[2] + lengthOfLines[3] + lengthOfLines[4] + lengthOfLines[5] + lengthOfLines[6] +
lengthOfLines[7] + lengthOfLines[8] + lengthOfLines[9]};
ifstream flights("flights.txt");
startingDeparturePoint = origin;
endDestinationPoint = destination;
totalFlightsPrice = 0;
totalFlightDuration = 0;
string originFromFile;
string destFromFile;
string airline;
int price;;
int flightDuration;
cout << "No. |" << "Origin |" << "Destination |" << "Airline |" << "Price |" << "Duration |" << endl;
cout << "----------------------------------------------------------------------------------------" << endl;
matches = 0;
int currentLine = 0;
while(flights >> originFromFile >> destFromFile >> airline >> price >> flightDuration)
{
//flights.seekg(setfilepos, ios::beg);
int numberOfChars = originFromFile.length() + destFromFile.length() + airline.length();
if(originFromFile == startingDeparturePoint && destFromFile == endDestinationPoint)
{
matches++;
directFlight(originFromFile, destFromFile, airline, price, flightDuration);
}
else if(originFromFile != startingDeparturePoint && destFromFile == endDestinationPoint)
{
matches++;
string stopoverLast = originFromFile;
string airlineLast = airline;
int priceLast = price;
int flightDurationLast = flightDuration;
int currentIndex = firstOrigins.size() + 1;
secondOrigins[currentIndex] = stopoverLast;
secondDests[currentIndex] = destFromFile;
secondAirlines[currentIndex] = airlineLast;
secondPrices[currentIndex] = priceLast;
secondFlightDurations[currentIndex] = flightDurationLast;
ifstream flights2("flights.txt");
string originFromFile2;
string destFromFile2;
string airlineFromFile2;
int priceFromFile2;
int flightDurationFromFile2;
while(flights2 >> originFromFile2 >> destFromFile2 >> airlineFromFile2 >> priceFromFile2 >> flightDurationFromFile2){//1q
if(destFromFile2 == stopoverLast){
firstOrigins.push_back(originFromFile2);
firstDests.push_back(destFromFile2);
firstAirlines.push_back(airlineFromFile2);
firstPrices.push_back(priceFromFile2);
firstFlightDurations.push_back(flightDurationFromFile2);
if(originFromFile2 != startingDeparturePoint){
thirdOrigins[currentIndex] = secondOrigins[currentIndex];
thirdDests[currentIndex] = secondOrigins[currentIndex];
thirdAirlines[currentIndex] = secondOrigins[currentIndex];
thirdPrices[currentIndex] = secondPrices[currentIndex];
thirdFlightDurations[currentIndex] = secondFlightDurations[currentIndex];
secondOrigins[currentIndex] = firstOrigins[currentIndex];
secondDests[currentIndex] = firstOrigins[currentIndex];
secondAirlines[currentIndex] = firstOrigins[currentIndex];
secondPrices[currentIndex] = firstPrices[currentIndex];
secondFlightDurations[currentIndex] = firstFlightDurations[currentIndex];
ifstream flights3("flights.txt");
string originFromFile3;
string destFromFile3;
string airlineFromFile3;
int priceFromFile3;
int flightDurationFromFile3;
while(flights3 >> originFromFile3 >> destFromFile3 >> airlineFromFile3 >> priceFromFile3 >> flightDurationFromFile3){
if(originFromFile3 == startingDeparturePoint && destFromFile3 == secondOrigins[currentIndex]){
firstOrigins[currentIndex] = originFromFile3;
firstDests[currentIndex] = destFromFile3;
firstAirlines[currentIndex] = airlineFromFile3;
firstPrices[currentIndex] = priceFromFile3;
firstFlightDurations[currentIndex] = flightDurationFromFile3;
while(flights3 >> originFromFile3 >> destFromFile3 >> airlineFromFile3 >> priceFromFile3 >> flightDurationFromFile3){
if(originFromFile3 == startingDeparturePoint && destFromFile3 == secondOrigins[currentIndex]){
firstOrigins.push_back(firstOrigins[currentIndex]);
firstDests.push_back(firstDests[currentIndex]);
firstAirlines.push_back(firstAirlines[currentIndex]);
firstPrices.push_back(firstPrices[currentIndex]);
firstFlightDurations.push_back(firstFlightDurations[currentIndex]);
secondOrigins[currentIndex + 1] = secondOrigins[currentIndex];
secondDests[currentIndex + 1] = secondDests[currentIndex];
secondAirlines[currentIndex + 1] = secondAirlines[currentIndex];
secondPrices[currentIndex + 1] = secondPrices[currentIndex];
secondFlightDurations[currentIndex + 1] = secondFlightDurations[currentIndex];
thirdOrigins[currentIndex + 1] = originFromFile3;
thirdDests[currentIndex + 1] = destFromFile3;
thirdAirlines[currentIndex + 1] = airlineFromFile3;
thirdPrices[currentIndex + 1] = priceFromFile3;
thirdFlightDurations[currentIndex + 1] = flightDurationFromFile3;
}
}
}
}
}
else{
currentIndex++;
while(flights >> originFromFile >> destFromFile >> airline >> price >> flightDuration){
if(originFromFile != startingDeparturePoint && destFromFile == endDestinationPoint){
matches++;
stopoverLast = originFromFile;
airlineLast = airline;
priceLast = price;
flightDurationLast = flightDuration;
secondOrigins[currentIndex] = stopoverLast;
secondDests[currentIndex] = destFromFile;
secondAirlines[currentIndex] = airlineLast;
secondPrices[currentIndex] = priceLast;
secondFlightDurations[currentIndex] = flightDurationLast;
firstOrigins.push_back(originFromFile2);
firstDests.push_back(destFromFile2);
firstAirlines.push_back(airlineFromFile2);
firstPrices.push_back(priceFromFile2);
firstFlightDurations.push_back(flightDurationFromFile2);
while(flights2 >> originFromFile2 >> destFromFile2 >> airlineFromFile2 >> priceFromFile2 >> flightDurationFromFile2){
currentIndex++;
secondOrigins[currentIndex] = stopoverLast;
secondDests[currentIndex] = destFromFile;
secondAirlines[currentIndex] = airlineLast;
secondPrices[currentIndex] = priceLast;
secondFlightDurations[currentIndex] = flightDurationLast;
firstOrigins.push_back(originFromFile2);
firstDests.push_back(destFromFile2);
firstAirlines.push_back(airlineFromFile2);
firstPrices.push_back(priceFromFile2);
firstFlightDurations.push_back(flightDurationFromFile2);
}
}
}
}
}
}
}
break;
}
// loop over vectors and print out results, put in conditional statements to
//check if 2nd and 3rd flights exist, if they do add the "-----" after
for(int i = 0; i < firstOrigins.size(); i++){
int mins = firstFlightDurations[i];
int hours = 0;
while(mins >= 60){
hours++;
mins -= 60;
}
cout << "No. |" << "Origin |" << "Destination |" << "Airline |" << "Price |"
<< "Duration " << endl;
if(firstOrigins[i] != "-"){
cout << left << setw(4) << setfill(' ') << 1 << right << "|";
cout << left << setw(7) << setfill(' ') << firstOrigins[i] << right << "|";
cout << left << setw(12) << setfill(' ') << firstDests[i] << right << "|";
cout << left << setw(20) << setfill(' ') << firstAirlines[i] << right << "|";
cout << left << "\x9c" << setw(13) << setfill(' ') << left << firstPrices[i] << right << "|";
cout << left << hours << "hr(s) " << mins << "min(s)" << setw(11) << setfill(' ') << right << "|" << endl;
if(secondOrigins[i] != "-"){
int mins2 = secondFlightDurations[i];
int hours2 = 0;
while(mins2 >= 60){
hours2++;
mins2 -= 60;
}
totalFlightsPrice = firstPrices[i] + secondPrices[i];
totalFlightDuration = firstFlightDurations[i] + secondFlightDurations[i] + thirdFlightDurations[i];
cout << left << setw(4) << setfill(' ') << 1 << right << "|";
cout << left << setw(7) << setfill(' ') << secondOrigins[i] << right << "|";
cout << left << setw(12) << setfill(' ') << secondDests[i] << right << "|";
cout << left << setw(20) << setfill(' ') << secondAirlines[i] << right << "|";
cout << left << "\x9c" << setw(13) << setfill(' ') << left << secondPrices[i] << right << "|";
cout << left << hours2 << "hr(s) " << mins2 << "min(s)" << setw(11) << setfill(' ') << right << "|" << endl;
if(thirdOrigins[i] != "-"){
int mins3 = secondFlightDurations[i];
int hours3 = 0;
while(mins3 >= 60){
hours3++;
mins3 -= 60;
}
totalFlightsPrice = firstPrices[i] + secondPrices[i] + thirdPrices[i];
totalFlightDuration = firstFlightDurations[i] + secondFlightDurations[i] + thirdFlightDurations[i];
cout << left << setw(4) << setfill(' ') << 1 << right << "|";
cout << left << setw(7) << setfill(' ') << thirdOrigins[i] << right << "|";
cout << left << setw(12) << setfill(' ') << thirdDests[i] << right << "|";
cout << left << setw(20) << setfill(' ') << thirdAirlines[i] << right << "|";
cout << left << "\x9c" << setw(13) << setfill(' ') << left << thirdPrices[i] << right << "|";
cout << left << hours3 << "hr(s) " << mins3 << "min(s)" << setw(11) << setfill(' ') << right << "|" << endl;
int totalmins = totalFlightsPrice;
int totalhours = 0;
while(totalmins >= 60){
totalhours++;
totalmins -= 60;
}
cout << left << setw(4) << setfill(' ') << " " << right << "|";
cout << left << setw(7) << setfill(' ') << " " << right << "|";
cout << left << setw(12) << setfill(' ') << " " << right << "|";
cout << left << setw(20) << setfill(' ') << " " << right << "|";
cout << left << setw(13) << setfill(' ') << "Total = \x9c" << totalFlightsPrice << right << "|";
cout << left << setw(6) << setfill(' ') << totalhours << "hr(s) " << totalmins << "min(s)"
<< setw(11) << setfill(' ') << right << "|" << endl;
cout << "----------------------------------------------------------------------------------------" << endl;
}
else{
int totalmins = totalFlightDuration;
int totalhours = 0;
while(totalmins >= 60){
totalhours++;
totalmins -= 60;
}
cout << left << setw(4) << setfill(' ') << " " << right << "|";
cout << left << setw(7) << setfill(' ') << " " << right << "|";
cout << left << setw(12) << setfill(' ') << " " << right << "|";
cout << left << setw(20) << setfill(' ') << " " << right << "|";
cout << left << setw(13) << setfill(' ') << "Total = \x9c" << totalFlightsPrice << right << "|";
cout << left << setw(6) << setfill(' ') << totalhours << "hr(s) " << totalmins << "min(s)"
<< setw(11) << setfill(' ') << right << "|" << endl;
cout << "----------------------------------------------------------------------------------------" << endl;
}
}
else{
cout << "----------------------------------------------------------------------------------------" << endl;
}
}
else{
cout << "No possible flight paths between the airports inputted.";
}
currentLine++;
if(filePointers[currentLine] != filePointers[currentLine - 1]){
flights.clear();
flights.seekg(filePointers[currentLine],ios::beg);
}
}
EDIT:
You can also ignore the checkNumOfLines file, and the filePointers and lengthOfLines arrays. I thought i had to reset the file pointer for it to print out correctly but nope. Just realised it does output one possible flight path which is if i input the very first origin and destination from the flight path i am reading in to the program.
EDIT 2:
This is giving me way more stress than it should be. i think this whole method i'm using is absurd. Can someone briefly outline an approach they would take to build a command line program that would show you a list of possible flights between two user inputted airport codes, allowing for up to 2 stops please.
NEW APPROACH (Thanks to #PaulMcKenzie and #TonyD):
I basically create 3 vectors, one to hold all the possible flights from the text file, one to hold the flights for the current journey (this gets cleared on each loop) and one which is a multidimensional vector to hold the series of flights as vectors that were in the current journey.
class flightSearch
{
public:
struct Flight
{
string origin;
string destination;
string airline;
int price;
int flightDuration;
};
vector<Flight> allFlights;
vector<Flight> flightsInJourney;
vector<vector <Flight> > allMatches;
Flight f;
void populateFlightsVector()
{
ifstream flightsfile("flights.txt");
while(flightsfile >> f.origin >> f.destination >> f.airline >> f.price >> f.flightDuration){
allFlights.push_back(f);
}
}
void searchForARoute(string userOrigin, string userDestination)
{
populateFlightsVector();
for(unsigned i = 0; i < allFlights.size(); i++)
{
flightsInJourney.clear();
if(allFlights[i].origin == userOrigin && allFlights[i].destination == userDestination)
{
flightsInJourney.insert(flightsInJourney.begin(), allFlights[i]);
}
allMatches.push_back(flightsInJourney);
}
for(unsigned i = 0; i < allMatches.size(); i++)
{
for(unsigned j = 0; j < allMatches[i].size(); j++){
cout << allMatches[i][j].origin << " " << allMatches[i][j].destination << " " << allMatches[i][j].airline << endl;
}
}
}
};
Now i should be able add some code to check for routes that require more than one flight as i did in my first attempt and add them to the end multidimensional vector. I've tested this code and it seems to work with direct flights so far. Feel free to call out anything that looks like it could be problematic.
With your latest code, here are the issues that I see that would cause some problems.
First, you don't need to have an flightsInJourney vector as a global variable, and thus repeatedly having to clear the vector in your searchForARoute function. You can make it local to your searchForARoute function, since all you're using it for is to collect all of the matching flights, and then copy these flights to your allMatches vector.
Second, you call populateFlightsVector in your search function, but that is not necessary. You are supposed to be populating the data file once and only once, not repeatedly. Better to put this in main() or similar function that gets called only once to set up your data.
Third, going back to the searchForARoute function, your loop to collect the flights that you find is not correct. You're supposed to collect all the flights found in a local vector first, and then when finished, you push_back this vector of found flights onto your allMatches vector.
So in a nutshell, the function would probably look more like this:
void searchForARoute(const string& userOrigin,
const string& userDestination)
{
vector<Flight> flightsInJourney;
for(size_t i = 0; i < allFlights.size(); i++)
{
if(allFlights[i].origin == userOrigin && allFlights[i].destination == userDestination)
flightsInJourney.push_back(allFlights[i]);
}
// push back all of the found matches
allMatches.push_back(flightsInJourney);
for(size_t i = 0; i < allMatches.size(); i++)
{
for(size_t j = 0; j < allMatches[i].size(); j++)
cout << allMatches[i][j].origin << " " << allMatches[i] [j].destination << " " << allMatches[i][j].airline << endl;
}
}
Related
I'm trying my best to get through a C++ online class and I'm currently writing a program to help a local restaurant automate its breakfast billing system. The program should do the following:
A. Show the customer the different breakfast items offered by the restaurant.
B. Allow the customer to select more than one item from the menu.
C. Calculate and print the bill.
Assume that the restaurant offers the following breakfast items (the price of each item is shown to the right of the item):
Plain Egg 1.45
Bacon & Egg 2.45
Muffin 0.99
French Toast 1.99
Fruit Basket 2.49
Cereal 0.69
Coffee 0.50
Tea 0.75
My code is at the bottom, my problem is with the while loop in the showMenu function. As an example say the user wants to order a Plain Egg. Then it will run line 104 orderTotal = menuList[0].menuPrice + orderTotal. That should mean 0 = 1.45 + 0 right? Afterwards it runs orderTax = orderTotal * 0.05 + orderTax. Which should mean 0 = 1.45 * 0.05 + 0 if I'm correct? My trouble is that both my orderTotal and orderTax remain at 0 when I cout << them. What can I do to fix this? I also know that my menuPrice variable is working because it displays their values on the menu. Thanks for taking the time to read my post.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
struct menuItemType
{
string menuItem;
double menuPrice;
};
void getData(menuItemType menuList[]);
void showMenu(menuItemType menuList[], double orderTotal, double orderTax, int orderCount[]);
void printCheck(menuItemType menuList[], double orderTotal, double orderTax, int orderCount[]);
int main()
{
menuItemType menuList[8];
double orderTotal = 0;
double orderTax = 0;
int orderCount[8]{ 0,0,0,0,0,0,0,0 };
getData(menuList);
showMenu(menuList, orderTotal, orderTax, orderCount);
printCheck(menuList, orderTotal, orderTax, orderCount);
return 0;
system("pause");
}
void getData(menuItemType menuList[]) // This function's purpose is to fill the array menuList[8] with the name and price of each item.
{
menuItemType plainEgg;
menuItemType baconEgg;
menuItemType muffin;
menuItemType frenchToast;
menuItemType fruitBasket;
menuItemType cereal;
menuItemType coffee;
menuItemType tea;
plainEgg.menuItem = "Plain Egg";
plainEgg.menuPrice = 1.45;
baconEgg.menuItem = "Bacon & Egg";
baconEgg.menuPrice = 2.45;
muffin.menuItem = "Muffin";
muffin.menuPrice = 0.99;
frenchToast.menuItem = "French Toast";
frenchToast.menuPrice = 1.99;
fruitBasket.menuItem = "Fruit Basket";
fruitBasket.menuPrice = 2.49;
cereal.menuItem = "Cereal";
cereal.menuPrice = 0.69;
coffee.menuItem = "Coffee";
coffee.menuPrice = 0.50;
tea.menuItem = "Tea";
tea.menuPrice = 0.75;
menuList[0] = plainEgg;
menuList[1] = baconEgg;
menuList[2] = muffin;
menuList[3] = frenchToast;
menuList[4] = fruitBasket;
menuList[5] = cereal;
menuList[6] = coffee;
menuList[7] = tea;
}
void showMenu(menuItemType menuList[], double orderTotal, double orderTax, int orderCount[]) // This function's purpose is to display the menu to the user for orders and calculate the total.
{
//Displays menu
cout << "\t" << "Welcome to Johnny's Restaurant" << endl;
cout << "\t" << "What would you like to order?" << endl;
cout << "\n" << endl;
cout << "\t" << "1. " <<menuList[0].menuItem << setw(10) << "$" << menuList[0].menuPrice << endl;
cout << "\t" << "2. " <<menuList[1].menuItem << setw(8) << "$" << menuList[1].menuPrice << endl;
cout << "\t" << "3. " <<menuList[2].menuItem << setw(13) << "$" << menuList[2].menuPrice << endl;
cout << "\t" << "4. " <<menuList[3].menuItem << setw(7) << "$" << menuList[3].menuPrice << endl;
cout << "\t" << "5. " <<menuList[4].menuItem << setw(7) << "$" << menuList[4].menuPrice << endl;
cout << "\t" << "6. " <<menuList[5].menuItem << setw(13) << "$" << menuList[5].menuPrice << endl;
cout << "\t" << "7. " <<menuList[6].menuItem << setw(13) << "$" << menuList[6].menuPrice << endl;
cout << "\t" << "8. " <<menuList[7].menuItem << setw(16) << "$" << menuList[7].menuPrice << endl;
cout << "\n" << endl;
bool orderActive = true; {};
int itemChoice;
//Prompts the user to pick from the menu
while (orderActive == true)
{
cout << "Select the number pertaining to which item you would like or press [0] to finish: ";
cin >> itemChoice;
if (itemChoice == 1)
{
orderTotal = menuList[0].menuPrice + orderTotal;
orderTax = orderTotal * 0.05 + orderTax;
orderCount[0] = orderCount[0] + 1;
cout << menuList[0].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 2)
{
orderTotal = menuList[1].menuPrice + orderTotal;
orderTax = orderTotal * 0.05 + orderTax;
orderCount[1] = orderCount[1] + 1;
cout << menuList[1].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 3)
{
orderTotal = menuList[2].menuPrice + orderTotal;
orderTax = orderTotal * 0.05 + orderTax;
orderCount[2] = orderCount[2] + 1;
cout << menuList[2].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 4)
{
orderTotal = menuList[3].menuPrice + orderTotal;
orderTax = orderTotal * 0.05 + orderTax;
orderCount[3] = orderCount[3] + 1;
cout << menuList[3].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 5)
{
orderTotal = menuList[4].menuPrice + orderTotal;
orderTotal * 0.05 + orderTax;
orderCount[4] = orderCount[4] + 1;
cout << menuList[4].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 6)
{
orderTotal = menuList[5].menuPrice + orderTotal;
orderTotal * 0.05 + orderTax;
orderCount[5] = orderCount[5] + 1;
cout << menuList[5].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 7)
{
orderTotal = menuList[6].menuPrice + orderTotal;
orderTotal * 0.05 + orderTax;
orderCount[6] = orderCount[6] + 1;
cout << menuList[6].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 8)
{
orderTotal = menuList[7].menuPrice + orderTotal;
orderTotal * 0.05 + orderTax;
orderCount[7] = orderCount[7] + 1;
cout << menuList[7].menuItem << " has been added to your order." << endl;
}
else if (itemChoice == 0)
{
orderActive = false;
}
else
{
cout << "Error Try Again" << endl;
}
}
cout << endl;
}
void printCheck(menuItemType menuList[], double orderTotal, double orderTax, int orderCount[]) // This function's purpose is to display the user's total
{
cout << "\n" << endl;
cout << "\t" << "Welcome to Johnny's Restaurant" << endl;
for (int x = 0; x < 1; x++)
{
if (orderCount[0] > 0)
{
cout << "\t" << orderCount[0] << setw(10) << menuList[0].menuItem << setw(15) << "$" << menuList[0].menuPrice << endl;
}
if (orderCount[1] > 0)
{
cout << "\t" << orderCount[1] << setw(12) << menuList[1].menuItem << setw(13) << "$" << menuList[1].menuPrice << endl;
}
if (orderCount[2] > 0)
{
cout << "\t" << orderCount[2] << setw(7) << menuList[2].menuItem << setw(18) << "$" << menuList[2].menuPrice << endl;
}
if (orderCount[3] > 0)
{
cout << "\t" << orderCount[3] << setw(13) << menuList[3].menuItem << setw(12) << "$" << menuList[3].menuPrice << endl;
}
if (orderCount[4] > 0)
{
cout << "\t" << orderCount[4] << setw(13) << menuList[4].menuItem << setw(12) << "$" << menuList[4].menuPrice << endl;
}
if (orderCount[5] > 0)
{
cout << "\t" << orderCount[5] << setw(7) << menuList[5].menuItem << setw(18)<< "$" << menuList[5].menuPrice << endl;
}
if (orderCount[6] > 0)
{
cout << "\t" << orderCount[6] << setw(7) << menuList[6].menuItem << setw(18) << "$" << menuList[6].menuPrice << endl;
}
if (orderCount[7] > 0)
{
cout << "\t" << orderCount[7] << setw(4) << menuList[7].menuItem << setw(21) << "$" << menuList[7].menuPrice << endl;
}
}
cout << "\t" << "Tax " << setw(22) << "$" << orderTax << endl;
cout << "\t" << "Amount Due: " << setw(14) << "$" << orderTotal << endl;
}
I'm making this student record program that my prof asked us to do. It keeps saying cannot convert 'StudRec' to 'StudRec' in assignment and sometimes it says cannot convert char* to const char*. StudRec is my struct variable and this is the function that should sort the recorded names alphabetically.
void sort_name(StudRec name[], StudRec temp[], int studcount)
{
if (studcount > 0)
{
for (int i=0; i<studcount; i++)
{
for (int j=studcount; j<=i; j++)
{
if(strcmp(name[j].nm, name[j+1].nm) > 0)
{
temp=name[j];
name[j]= name[j+1];
name[j+1]= temp;
}
}
}
cout << "\t| |\t\t\t The records have been sorted alphabetically by name.\n";
}
else
{
cout << "\t| |\t\t\t There is no current record to sort by name.\n\n";
}
}
Ok, assuming that the StudRec has all necessary operations (assignment, default constructor, etc.), you don't need to pass an array of temp values:
void sort_name(StudRec name[], int studcount)
{
StudRec temp;
// ...
}
That should fix one issue: you are trying to assign an element to the whole array:
temp=name[j];
Even better would be to define temp right where you use it:
const StudRec temp = name[j];
Anyway, I guess you are trying to implement a BubbleSort, and your implementation is incorrect because of the indexing. Should be:
for (int i = 1; i < studcount; ++i)
for (int j = 0; j < studcount - i; ++j)
This is the code in the fGrade function:
void fGrade(StudRec rec[], int studcount)
{
string id;
if (studcount > 0)
{
cout << "\n\n\t| |\t\t =====================================================\n";
cout << "\t| |\t\t\t\t STUDENT'S FINAL GRADE \n";
cout << "\t| |\t\t =====================================================\n\n";;
check: cout << "\n\t| |\t\t\t Enter student's ID Number: ";
cin >> id;
int index = search(rec, id, studcount);
if (index != -1 && studcount > 0)
{
rec[index].fgrd = (((rec[index].quiz / 150) * 100) * 0.2) + (((rec[index].hw / 20) * 100) * 0.1) + (((rec[index].midT / 100) * 100) * 0.15)
+ (((rec[index].fExam / 100) * 100) * 0.15) + (((rec[index].acts / 150) * 100) * 0.25) + (((rec[index].proj / 100) * 100) * 0.15);
cout << left << setw(10) << "\n ID No." << setw(30) << "NAME" << setw(15) << "FINAL GRADE" << setw(10) << "REMARKS";
cout << "\n ------------------------------------------------------------\n";
cout << " " << left << setw(8) << rec[index].id << setw(30) << rec[index].nm << setw(15) << fixed << setprecision(2) << rec[index].fgrd;
if (rec[index].fgrd >= 75 && rec[index].fgrd <= 100)
{
cout << setw(10) << "Passed\n\n";
}
else if (rec[index].fgrd < 75)
{
cout << setw(10) << "Failed\n\n";
}
}
else
{
cout << "\t| |\t\t\t This record does not exist. Check your ID and try again.";
goto check;
}
}
else
{
cout << "\t| |\t\t\t There is no current record to calculate a final grade.\n\n";
return;
}
}
and this is the code for the view_rec function:
void view_rec(StudRec rec[], int studcount)
{
if (studcount > 0)
{
cout << "\n\n\t| |\t\t ===================================================\n";
cout << "\t| |\t\t\t\t VIEW STUDENT RECORD \n";
cout << "\t| |\t\t ===================================================\n\n";
int i=0;
cout << "\n\t| |\t\t " << left << setw(10) << "ID" << setw(30) << "NAME" << setw(7) << "SEX" << setw(10) << "QUIZ";
cout << setw(14)<< "ASSIGNMENT" << setw(11) << "MIDTERM" << setw(14) << "FINAL EXAM" << setw(12) << "ACTIVITY";
cout << setw(11)<< "PROJECT" << setw(9) << "TOTAL\n";
cout << "\t| |\t\t " << "----------------------------------------------------------------------------------------------------------------------------\n\n";
while(i <= studcount)
{
if(rec[i].id != "")
{
cout << "\t| |\t\t " << left << setw(10) << rec[i].id << setw(30) << rec[i].nm << setw(7) << rec[i].sex;
cout << setw(10) << rec[i].quiz << setw(14) << rec[i].hw << setw(11) << rec[i].midT;
cout << setw(14) << rec[i].fExam << setw(12) << rec[i].acts << setw(11) << rec[i].proj << setw(9) << rec[i].total;
cout << endl << endl;
}
i+=1;
}
}
else
{
cout << "\t| |\t\t\t There is no current record to view.\n\n";
return;
}
}
I'm trying to make a football tournament in C++, in which the user inputs the name of the teams(8 teams) and then each team has to play with the other one 1 time. Firstly, I don't know how to read the team names, I mean I tried to use .getline or just cin of a char array, but then I need to put the teams into the matrix and after the final game my program should print the table. So there's the first question: how to read the names and basically make the program think they are numbers or does it work with just with names, no need to use int? And then the users inputs the result for every game, but here comes the hard part. After all the results have been introduced, the matrix rotates cyclic and then the result stored in the variables(you will see in code victory/losses) overwrites themselves, so at the end, I cannot print the right table. So that's the second question: How can I make them store to the right 'team' while they rotate? Sorry if I didn't quite explain very well how it works, hope you understand it. Cheers!
// FOOTBALL TOURNAMENT
int map[2][4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << "map[" << i << "][" << j << "]= ";
cin >> map[i][j];
}
}
cout << "The map looks like this:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
map[0][0] = 1;
int temp = 0, temp2 = 0, temp3 = 0, temp4 = 0, temp5 = 0, temp6 = 0;
int a, b, c, d, e, f, g, h, round = 0;
int victory_m00(0), losses_m10(0), victory_m10(0), losses_m00(0), victory_m01(0), losses_m11(0), victory_m11(0), losses_m01(0);
int victory_m02(0), losses_m12(0), victory_m12(0), losses_m02(0), victory_m03(0), losses_m13(0), victory_m13(0), losses_m03(0);
do
{
// Insert result for every game
cout << "Enter the result of the first game between " << map[0][0] << " vs. " << map[1][0] << endl;
cin >> a >> b;
if (a > b) {
victory_m00++;
losses_m10++;
}
else if (a < b)
{
victory_m10++;
losses_m00++;
}
cout << "Enter the result of the first game between: " << map[0][1] << " vs. " << map[1][1] << endl;
cin >> c >> d;
if (c > d) {
victory_m01++;
losses_m11++;
}
else if (c < d)
{
victory_m11++;
losses_m01++;
}
cout << "Enter the result of the first game between: " << map[0][2] << " vs. " << map[1][2] << endl;
cin >> e >> f;
if (e > f) {
victory_m02++;
losses_m12++;
}
else if (e < f)
{
victory_m12++;
losses_m02++;
}
cout << "Enter the result of the first game between: " << map[0][3] << " vs. " << map[1][3] << endl;
cin >> g >> h;
if (g > h) {
victory_m03++;
losses_m13++;
}
else if (g < h)
{
victory_m13++;
losses_m03++;
}
round++;
// Map switching
temp = map[1][0];
map[1][0] = map[0][1];
temp2 = map[1][1];
map[1][1] = temp;
temp3 = map[1][2];
map[1][2] = temp2;
temp4 = map[1][3];
map[1][3] = temp3;
temp5 = map[0][3];
map[0][3] = temp4;
temp6 = map[0][2];
map[0][2] = temp5;
map[0][1] = temp6;
// Table calculating and printing ~ also this has to be outside the loop (but at first i wanted to print the table after every 'round'
cout << "This is how the table looks like after the " << round << " round: \n";
cout << map[0][0] << " has: " << victory_m00 << " victory(-ies) and " << losses_m00 << " loss-es!\n";
cout << map[0][1] << " has: " << victory_m01 << " victory(-ies) and " << losses_m01 << " loss-es!\n";
cout << map[0][2] << " has: " << victory_m02 << " victory(-ies) and " << losses_m02 << " loss-es!\n";
cout << map[0][3] << " has: " << victory_m03 << " victory(-ies) and " << losses_m03 << " loss-es!\n";
cout << map[1][0] << " has: " << victory_m10 << " victory(-ies) and " << losses_m10 << " loss-es!\n";
cout << map[1][1] << " has: " << victory_m11 << " victory(-ies) and " << losses_m11 << " loss-es!\n";
cout << map[1][2] << " has: " << victory_m12 << " victory(-ies) and " << losses_m12 << " loss-es!\n";
cout << map[1][3] << " has: " << victory_m13 << " victory(-ies) and " << losses_m13 << " loss-es!\n";
cout << endl;
cout << endl;
} while (map[0][1] != 2);
```
I have been reading about setw for column widths, however setting a width for each colum does not seem to be aligning the last two columns. I have tried using the right align, however it also changes alignment for the left two columns as well, which I don't want. In the end I'd like everything to be left aligned. Is there an easier way of doing this other than setw?
Current code:
void print_head()
{
cout.setf(ios::left);
cout << setw(16) << "Operation"
<< setw(32) << "z"
<< setw(8) << "Cost"
<< setw(8) << "Total" << endl;
for (int i=0; i<64; ++i) cout << "-";
cout << endl;
}
print_head();
cout.setf(ios::left);
cout << setw(16) << "Initial String"
<< setw(32) << test1
<< setw(8) << "0"
<< setw(8) << "0" << endl;
for (int g = minops[0] + minops[1] - 1;g>-1;g--){
string a;
for(stringstream ss(operations[g]); getline(ss, a, ','); ) // that's all !
v.push_back(a);
//cout << v[current] << "\n";
if (v[current] == "c"){
z = sright(z, cursorg);
current++;
cout << setw(16) << "right"
<< setw(32) << z
<< setw(8) << "0"
<< setw(8) << tcost << endl;
}else if (v[current] == "d"){
z = sdelete(z, cursorg);
size = size - 1;
tcost = tcost + 2;
cout << setw(16) << "delete"
<< setw(32) << z
<< setw(8) << "2"
<< setw(8) << tcost << endl;
//cout << "cursor out of delete: " << cursorg << "\n";
current = current + 2;
}else if (v[current] == "r"){
z = sreplace(z, cursorg, test2, stoi(v[current+1]), stoi(v[current+2]));
int printtemp = stoi(v[current+2]);
string s(1,test2[printtemp]);
string tempstr = "replace by " + s;
tcost = tcost + 4;
cout << setw(16) << tempstr
<< setw(32) << z
<< setw(8) << "4"
<< setw(8) << tcost << endl;
current = current + 3;
}else if (v[current] == "i"){
z = sinsert(z, test2, cursorg, stoi(v[current+1]));
size = size - 1;
tcost = tcost + 3;
int printtemp = stoi(v[current+1]);
string s(1,test2[printtemp]);
string tempstr = "insert " + s;
cout << setw(16) << tempstr
<< setw(32) << z
<< setw(8) << "3"
<< setw(8) << tcost << endl;
current = current + 2;
}else{
}
//cout << operations[g] << "\n";
//cout << "z is: " << z << "\n";
}
cout << "\n";
cout << "minimum operations is: " << minops[0] << "\n";
This is my current output, however I want the cost and total cost to be a neat aligned column under the header. How do I use setw to fix my alignment?
Delete implementation:
string sdelete(string input, int &cursor){ //deletes the letter under the cursor, cost 2
if (cursor == (input.length() + 1)){
//do nothing
}else{
input[cursor] = NULL;
cursor = cursor+1;
}
//DEBUG cout << "delete input: " << input << "\n";
//DEBUG cout << "cursor in delete: " << cursor << "\n";
return input;
}
I'm trying to left justify one side of a line and right justify the other side of the line, but im having trouble getting the right side to right justify. Could anyone catch my error?
//The following program will declare
#include <iostream>
#include <iomanip>
using namespace std;
const int HOUSING = 3500; //housing cost
const int MEALS = 2000; //meal cost
const int N_CRED_PER = 285; //out of state credit cost
const int CRED_PER = 130; //amount of money per credit(cost)
const int TAB = 30; //precision
const int ADD_FEES = 6200; //out of state fees for non-resident
int main()
{
cout << "Grant Mercer section 1002 Assignment 6\n\n";
int size, studentID, credits, i, valid,total;
//size of loop, studentID to hold ID of student, credits to hold num
//of credits the student will take, i to start loop
char first, last, res, housing, meal; //first and last to hold initials of
//student, res to hold code
//if student is resident, meal to hold
//code if student has meals
cin >> size; //grab length of loop in file
cout << left; //manipulate stream
cout << fixed << showpoint << setprecision(2);
valid = size; //initially all entries are valid, but de
//cremented each time something goes wrong
while (i < size)
{
cin >> studentID >> first >> last >> credits >> res; //read in mandatory data to vars
cout << setw(TAB) << left << "Student #: " << right << studentID << endl; //display id
cout << setw(TAB) << left << "Initials: " << right << first << last << endl;//display initials
if(credits > 0 && credits < 21) //if credits are fine
{
switch(res) //find char in res
{
case 'R': //if RESIDENT
case 'r':
cout << setw(TAB) << left << "Residency status: " << right << "Resident" << endl;
cout << setw(TAB) << left << "Credits: " << right << credits << endl;
cout << setw(TAB-10) << left << "Tuition: " << setw(10) << "$" << right << (double)CRED_PER * credits << endl;
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double)CRED_PER * credits << endl;
total += CRED_PER * credits; //add to total cost
break;
case 'N': //if NON-RESIDENT
case 'n':
cout << setw(TAB) << left << "Residency status: " << right << "Non-resident" << endl;
cin >> housing >> meal; //since the student is non-resident, they
//have a mean and house code
cout << setw(TAB) << left << "Credits: " << right << credits << endl;
cout << setw(TAB - 10) << left << "Tuition: " << setw(10) << "$" << right << (double)credits * N_CRED_PER + ADD_FEES << endl;
if(housing == 'H' || housing == 'h')
{
cout << setw(TAB - 10) << left << "Housing: " << setw(10) << "$" << right << (double)HOUSING << endl;
if(meal == 'M' || meal == 'm') //if MEALS
{
cout << setw(TAB-10) << left << "Meal Plan: " << setw(10) << "$" << right << (double) MEALS << endl;
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double) MEALS + HOUSING + (credits * N_CRED_PER) + ADD_FEES << endl;
total += MEALS + HOUSING + (credits * N_CRED_PER) + ADD_FEES;
//add to total
}
else //if NO MEALS
{
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double)\
HOUSING + (credits *N_CRED_PER) + ADD_FEES << endl;
total += HOUSING + (credits * N_CRED_PER) + ADD_FEES;
//add to total
total += HOUSING + (credits * N_CRED_PER) + ADD_FEES;
//add to total
}
}
else //if NO HOUSING NO MEALS
{
cout << setw(TAB-10) << left << "Total due: " << setw(10) << "$" << right << (double)(cr\
edits * CRED_PER) + ADD_FEES
<< endl;
total += (credits * CRED_PER) + ADD_FEES;
}
break;
}
}
else
{
cout << "INVLIAD CREDIT AMOUNT...\n";
valid--;
}
i++;
cout << endl << endl;
}
cout << "\nFINAL TOTALS\n"; //display final totals from students
cout << right << setw(TAB) << left << "Valid request count: " << right << valid << endl;
cout << setw(TAB) << left << "Invalid requrest count: " << right << size - valid << endl;
cout << setw(TAB - 10) << left << "Total feed due: " << setw(10) << "$" << right << (double)total;
cout << endl;
return 0;
}
the output is all left justified, i dont understand what i need to do to make this all right justified. Thanks!
You're forgetting to use setw() before printing each right aligned string with cout. For example, take the following line in your code:
cout << setw(TAB) << left << "Residency status: " << right << "Resident" << endl;
Before printing each string justified to the left or right, you must set a new width:
cout << setw(20) << left << "Residency status: " << setw(20) << right << "Resident" << endl;
Without a setw(), it assumes the width is zero, which basically ignores the right alignment.