Aligning output column using setw in C++ - c++

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

Related

Football tournament with matrix

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 an issue with recursive minmaxi function (well two functions) in a chess program

My recursive functions should be testing moves from black_move_list for b_maxi and white_move_list for maxi, but the program is returning '#' 7 1 -> 7 3, for example, which means 'space' from 'h2 to h4.' Despite this, the move list generated in the same function call does not contain this move. All of the function calls pass the position class by value, not reference, so I don't see how the recursive calls could modify the higher level move list. The move list is contained in a vector, but that shouldn't make any difference as far as I know. Does anyone see a glaring error in my code? (Please ignore the desperate debug attempt outputs).
Here is my main.cpp code:
//chess engine 2.0
#include <iostream>
#include "position.h"
#include "evaluate.h"
using namespace std;
int maxi(position board1, int depth);
int b_maxi(position board1, int depth);
move_params best_white_move;
move_params best_black_move;
const bool CLEAR = 1;
const bool DO_NOT_CLEAR = 0;
const bool WHITE = 1;
const bool BLACK = 0;
const int DEPTH = 3;
int input = 42;
int main()
{
position test_game;
evaluate evaluator;
int col1, row1, col2, row2;
while(input != 10){
cout << "Enter a command: \n"
<< "0 (print board)\n"
<< "1 (find legal white moves)\n"
<< "2 (find legal black moves)\n"
<< "3 (print white move list)\n"
<< "4 (print black move list)\n"
<< "5 (piece move)\n"
<< "6 (evaluate position for white)\n"
<< "7 (evaluate position for black)\n"
<< "8 (find best white move)\n"
<< "10 (exit program)\n";
cin >> input;
switch(input){
case 0:
test_game.print_board();
break;
case 1:
test_game.find_legal_moves(WHITE);
break;
case 2:
test_game.find_legal_moves(BLACK);
break;
case 3:
test_game.print_move_list('w');
break;
case 4:
test_game.print_move_list('b');
break;
case 5:
cout << "Piece move. Enter col, row, new_col new_row:\n";
cin >> col1 >> row1 >> col2 >> row2;
test_game.move(col1,row1,col2,row2, CLEAR);
break;
case 6:
cout << "Evaluating the position for white...\n";
cout << "score = " << evaluator.evaluate_position(test_game,WHITE) << endl;
break;
case 7:
cout << "Evaluating the position for black...\n";
cout << "score = " << evaluator.evaluate_position(test_game,BLACK) << endl;
break;
case 8:
cout << "Finding best move for white...\n";
cout << "estimated move value: " << maxi(test_game, DEPTH) << endl;
cout << "piece: " << best_white_move.piece << endl;
cout << "new col: " << best_white_move.new_col << endl;
cout << "new row: " << best_white_move.new_row << endl;
cout << "old col: " << best_white_move.col << endl;
cout << "old row: " << best_white_move.row << endl;
break;
}
}
return 0;
}
int maxi(position board1, int depth){
int score = 0;
evaluate evaluator;
if(depth == 0) return evaluator.evaluate_position(board1, WHITE);
int max = -109009000;
//cout << "max initialized to " << max << endl; //DEBUG
board1.find_legal_moves(WHITE);
for(int i = 0; i < board1.white_move_list.size();i++){
int new_row = board1.white_move_list[i].new_row;
int new_col = board1.white_move_list[i].new_col;
int old_row = board1.white_move_list[i].row;
int old_col = board1.white_move_list[i].col;
char temp_piece = board1.board[new_col][new_row];
//now move,
//DEBUG ZONE BEGIN - before move
bool next_check = false;//debugdebug
if(depth == DEPTH-2 && board1.board[old_col][old_row] == '#'){
board1.print_move_list('w');
cout << "before move\n";
cout << "piece: " << board1.board[old_col][old_row] << "\n"; //DEBUG
cout << "move coords: " << old_col << " " << old_row
<< "->" << new_col << " " << new_row << "\n"; //DEBUG
cout << "depth == " << depth << "\n";//DEBUG
board1.print_board();//DEBUG
}
board1.move(old_col,old_row,new_col,new_row, DO_NOT_CLEAR);
//DEBUG ZONE BEGIN - before b_max,but after move
if(depth == DEPTH-2 && board1.board[new_col][new_row] == '#'){
cout << "before b_max\n";
cout << "piece: " << board1.board[new_col][new_row] << "\n"; //DEBUG
cout << "max move coords: " << old_col << " " << old_row
<< "->" << new_col << " " << new_row << "\n"; //DEBUG
cout << "depth == " << depth << "\n";//DEBUG
board1.print_board();//DEBUG
}
//call b_maxi,
score = -b_maxi(board1, depth - 1);
//DEBUG ZONE BEGIN - after_bmaxi
if(depth == DEPTH-2 && board1.board[new_col][new_row] == '#'){
cout << "after_bmaxi";
cout << "piece: " << board1.board[new_col][new_row] << "\n"; //DEBUG
cout << "max move coords: " << old_col << " " << old_row
<< "->" << new_col << " " << new_row << "\n"; //DEBUG
cout << "depth == " << depth << " & score == " << score << "\n";//DEBUG
board1.print_board();//DEBUG
next_check = true;
}
//DEBUG ZONE END
//update score and GLOBAL best white move if in main depth,
if(score > max){
max = score;
if(depth == DEPTH){
best_white_move.piece = board1.board[new_col][new_row];
best_white_move.col = old_col;
best_white_move.row = old_row;
best_white_move.new_col = new_col;
best_white_move.new_row = new_row;
}
}
if(depth == DEPTH-2){
//cout << "new max = " << max << "\n\n";//DEBUG
//cout << "\n\nspace\n\n";//DEBUG
}
//and unmove
board1.board[old_col][old_row] = board1.board[new_col][new_row];
board1.board[new_col][new_row] = temp_piece;
//DEBUG
if(next_check){
cout << "board after 'unmove':\n";
board1.print_board();
cout << "\n\n";
}
}
return max;
}
int b_maxi(position board1, int depth){
int score = 0;
evaluate evaluator;
if(depth == 0){
int ret_val = evaluator.evaluate_position(board1, BLACK);
//cout << "return val from mini = " << ret_val << "\n\n";
return ret_val;
}
int max = -109000900;
board1.find_legal_moves(BLACK);
for(int i = 0; i < board1.black_move_list.size();i++){
int new_row = board1.black_move_list[i].new_row;
int new_col = board1.black_move_list[i].new_col;
int old_row = board1.black_move_list[i].row;
int old_col = board1.black_move_list[i].col;
char temp_piece = board1.board[new_col][new_row];
//now move,
board1.move(old_col,old_row,new_col,new_row, DO_NOT_CLEAR);
//call maxi,
//cout << "depth = " << depth << ", " << "new min board: " << "\n\n"; //DEBUG
//board1.print_board();//DEBUG
//cout << "\n\n";//DEBUG
score = -maxi(board1, depth - 1);
/*DEBUG ZONE BEGIN
if(depth == DEPTH-1){
cout << "piece: " << board1.board[new_col][new_row] << "\n"; //DEBUG
cout << "B_max move coords: " << old_col << " " << old_row
<< "->" << new_col << " " << new_row << "\n"; //DEBUG
cout << "depth == " << depth << " & score == " << score << "\n";//DEBUG
board1.print_board();//DEBUG
}
//DEBUG ZONE END*/
//cout << "mini, depth = " << depth << "score after maxi call = " << score << "\n\n";//DEBUG
//update score and GLOBAL best black move,
if(score > max){
max = score;
if(depth == DEPTH){
best_black_move.piece = board1.board[new_col][new_row];
best_black_move.col = old_col;
best_black_move.row = old_row;
best_black_move.new_col = new_col;
best_black_move.new_row = new_row;
}
}
if(depth == DEPTH-1){
//cout << "new B_max = " << max << "\n";//DEBUG
//cout << "\n\nspace\n\n";//DEBUG
}
//and unmove
board1.board[old_col][old_row] = board1.board[new_col][new_row];
board1.board[new_col][new_row] = temp_piece;
}
return max;
}

function doesn't output anything from the vectors C++

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

C++: Append string to output of first and last array index in loop

I tried to word the title as best as I could. Here I have a function that indexes through two parallel arrays and then outputs them with some formatting.
void outputTable(string salsa_jars[], int jars_sold[], int index[])
{
int totalSold = 0;
cout << setw(8) << "\nSalsa type sells: " << endl
<< "-------------------------------" << endl;
for(int i = 0; i <= (SALSA_TYPES-1); i++)
{
totalSold += jars_sold[index[i]];
cout << setw(15) << left << salsa_jars[index[i]]
<< setw(15) << right << jars_sold[index[i]] << endl;
}
cout << "-------------------------------" << endl
<< "Total sales: " << setw(17) << totalSold << endl;
}
What I'm trying to achieve is to add a string to the first and last outputs of the array. Below is my attempt.
void outputTable(string salsa_jars[], int jars_sold[], int index[])
{
int totalSold = 0;
cout << setw(8) << "\nSalsa type sells: " << endl
<< "-------------------------------" << endl;
for(int i=0;i<=(SALSA_TYPES-1);i++)
{
if(i == 0){
cout << setw(7) << left << salsa_jars[index[i]]
<< "(Highest)" << setw(14) << right
<< jars_sold[index[i]] << endl;
}
else if (i == (SALSA_TYPES-1)){
cout << setw(7) << left << salsa_jars[index[i]]
<< "(Lowest)" << setw(15) << right
<< jars_sold[index[i]] << endl;
}
else{
totalSold += jars_sold[index[i]];
cout << setw(15) << left << salsa_jars[index[i]]
<< setw(15) << right << jars_sold[index[i]] << endl;
}
}
cout << "-------------------------------" << endl
<< "Total sales: " << setw(17) << totalSold << endl;
}
But the code seems redundant, and I couldn't think of any other way to do it. If anyone has any pointers, I would appreciate it. Thanks.
Just prepare appropriate title for entry, and use common logic for displaying it:
for(int i=0;i<=(SALSA_TYPES-1);i++)
{
string title = toString(salsa_jars[index[i]]);
if(i == 0){
title += " (Highest)";
}
else if (i == (SALSA_TYPES-1)){
title += " (Lowest)";
}
totalSold += jars_sold[index[i]];
cout << setw(15) << left << title
<< setw(15) << right << jars_sold[index[i]] << endl;
}
}

Iomanip errors with std::left/right

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.