I'm programming a checkers game as a form of practice for object-oriented design. The error I'm getting is the following:
First the code:
#include <iostream>
#include <stdio.h>
using namespace std;
class Piece {
public:
int ypos, xpos, index;
string color, kind;
int getY(void)
{
return ypos;
}
int getX(void)
{
return xpos;
}
int adjustY(int change)
{
ypos = ypos + change;
}
int adjustX(int change)
{
xpos = xpos + change;
}
};
int form(void)
{
string p[24];
for (int i = 0; i <= 23; ++i)
{
if (i < 4)
{
Piece p[i];
p[i].color = "white";
p[i].ypos = 7;
p[i].xpos = i * 2;
p[i].index = i;
p[i].kind = "peon";
}
else if (i < 8)
{
int l;
l = i - 4;
Piece p[i];
p[i].color = "white";
p[i].ypos = 6;
p[i].xpos = 1 + (l * 2);
p[i].index = i;
p[i].kind = "peon";
}
else if (i < 12)
{
int m;
m = i - 8;
Piece p[i];
p[i].color = "white";
p[i].ypos = 5;
p[i].xpos = (m * 2);
p[i].index = i;
p[i].kind = "peon";
}
else if (i < 16)
{
int n;
n = i - 12;
Piece p[i];
p[i].color = "black";
p[i].ypos = 0;
p[i].xpos = 1 + (n * 2);
p[i].index = i;
p[i].kind = "peon";
}
else if (i < 20)
{
int pp;
pp = i - 16;
Piece p[i];
p[i].color = "black";
p[i].ypos = 1;
p[i].xpos = (pp * 2);
p[i].index = i;
p[i].kind = "peon";
}
else
{
int q;
q = i - 20;
Piece p[i];
p[i].color = "black";
p[i].ypos = 2;
p[i].xpos = 1 + (q * 2);
p[i].index = i;
p[i].kind = "peon";
}
}
}
char matrix[8][8];
int printt(void)
{
for (int i = 0; i = 7; ++i)
{
for (int j = 0; j = 7; ++j)
{
matrix[i][j] = '_';
}
}
for (int c = 0; c <= 23;++c)
{
int a, b;
a = p[c].ypos;
b = p[c].xpos;
switch(p[c].kind)
{
case "peon":
switch(p[c].color)
{
case "white":
matrix[a][b] = 'o';
break;
case "black":
matrix[a][b] = 'x';
break;
}
break;
case "damen":
switch(p[c].color)
{
case "white":
matrix[a][b] = 'O';
break;
case "black":
matrix[a][b] = 'X';
break;
}
break;
}
}
cout << " 0|1|2|3|4|5|6|7| X Position (column)(j)" << endl;
cout << endl;
cout << "0 " << matrix[0][0] << "|" << matrix[0][1] << "|" << matrix[0][2] << "|" << matrix[0][3] << "|" << matrix[0][4] << "|" << matrix[0][5] << "|" << matrix[0][6] << "|" << matrix[0][7] << endl;
cout << "0 " << matrix[1][0] << "|" << matrix[1][1] << "|" << matrix[1][2] << "|" << matrix[1][3] << "|" << matrix[1][4] << "|" << matrix[1][5] << "|" << matrix[1][6] << "|" << matrix[1][7] << endl;
cout << "0 " << matrix[2][0] << "|" << matrix[2][1] << "|" << matrix[2][2] << "|" << matrix[2][3] << "|" << matrix[2][4] << "|" << matrix[2][5] << "|" << matrix[2][6] << "|" << matrix[2][7] << endl;
cout << "0 " << matrix[3][0] << "|" << matrix[3][1] << "|" << matrix[3][2] << "|" << matrix[3][3] << "|" << matrix[3][4] << "|" << matrix[3][5] << "|" << matrix[3][6] << "|" << matrix[3][7] << endl;
cout << "0 " << matrix[4][0] << "|" << matrix[4][1] << "|" << matrix[4][2] << "|" << matrix[4][3] << "|" << matrix[4][4] << "|" << matrix[4][5] << "|" << matrix[4][6] << "|" << matrix[4][7] << endl;
cout << "0 " << matrix[5][0] << "|" << matrix[5][1] << "|" << matrix[5][2] << "|" << matrix[5][3] << "|" << matrix[5][4] << "|" << matrix[5][5] << "|" << matrix[5][6] << "|" << matrix[5][7] << endl;
cout << "0 " << matrix[6][0] << "|" << matrix[6][1] << "|" << matrix[6][2] << "|" << matrix[6][3] << "|" << matrix[6][4] << "|" << matrix[6][5] << "|" << matrix[6][6] << "|" << matrix[6][7] << endl;
cout << "0 " << matrix[7][0] << "|" << matrix[7][1] << "|" << matrix[7][2] << "|" << matrix[7][3] << "|" << matrix[7][4] << "|" << matrix[7][5] << "|" << matrix[7][6] << "|" << matrix[7][7] << " Y Position (line)(i)" << endl;
cout << endl;
}
int main()
{
form();
printt();
cout << "End of Programm" << endl;
system ("pause");
return 0;
}
Then the error:
In function 'int printt()':
Line 130 Col 7 [Error] 'p' was not declared in this scope
I assume the problem is that the objects were created in an outside function. However, using extern creates more problems than I already have, and creating them outside a function is not possible, for the "for (int i=0;i<=23;++i)" statement needs to happen inside a function.
My question is: How do I call these objects (Piece p[0], Piece p[1], and so on) to the printt() function ?
Thank you very much, sorry if the question is dumb, I am pretty new to programming.
You should put this definition:
Piece p[24];
at the global scope, i.e. for instance just before the definition of f:
Piece p[24];
int form(void)
{
for (int i = 0; i <= 23; ++i)
The way you are referencing these objects in the printt function is correct.
Also, you should remove the
Piece p[i];
statements from the int from() implementation.
Also, you may want to implement a default constructor for your Piece class, to ensure that instances' int fields will be reasonably initialized on construction.
Related
I need to write an algorithm to optimally partition an array of N elements into K parts where the difference between the sums of the elements in each part is minimal (where all of the parts are as equivalent to one another as possible). The order of elements in the array must not be reordered. I need to find the array indices that will result in the optimal partition.
I have seen similar problems posted here, but none quite as abstract and complicated. I am currently taking a C++ algorithms class, but this is for a personal/side project, not any sort of assignment.
Here's some very rough starter code that attempts to use recursion to partition the array and even out the partitions, but the result is far from optimal, and I'm not even sure I'm on the right track. I'm guessing there's a far better algorithm out there somewhere. Any guidance would be appreciated.
#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
using namespace std;
void books(ifstream&);
void calculate(vector<int>&, vector<string>&, int, int, int, int, bool&, int&);
int main(int argc, const char * argv[]) {
vector<int> list;
vector<string> days;
int num;
ifstream fin("list.txt");
while(fin >> num) {
list.push_back(num);
}
fin.close();
int wordsPerBook = 0;
for (auto i : list) {
wordsPerBook += i;
cout << i << " ";
}
cout << endl;
int numDays = 8;
int wordsPerDay = wordsPerBook / numDays;
cout << "wordsPerBook: " << wordsPerBook << endl;
cout << "wordsPerDay: " << wordsPerDay << endl << endl;
int start = 0, day = 1;
int minOverPlus1Error = INT_MAX;
bool extraDay = false;
calculate(list, days, start, day, numDays, wordsPerDay, extraDay, minOverPlus1Error);
cout << endl << "Days: " << endl;
for (auto i : days)
cout << i << endl;
cout << endl;
if (extraDay && day == 1) {
extraDay = false;
cout << endl << "*********************Re-Calculate*********************" << endl;
days.clear();
days.shrink_to_fit();
calculate(list, days, 0, day, numDays, wordsPerDay, extraDay, minOverPlus1Error);
}
cout << endl << "Days: " << endl;
for (auto i : days)
cout << i << endl;
cout << endl;
if (extraDay && day == 1) {
extraDay = false;
cout << endl << "*********************Re-Calculate*********************" << endl;
days.clear();
days.shrink_to_fit();
calculate(list, days, 0, day, numDays, wordsPerDay, extraDay, minOverPlus1Error);
}
cout << endl << "Days: " << endl;
for (auto i : days)
cout << i << endl;
cout << endl;
return 0;
}
void calculate(vector<int>& list, vector<string>& days, int start, int day, int numDays, int wordsPerDay, bool& extraDay, int& minOverPlus1Error) {
int sumUnder = 0, sumOver = 0, sumUnderMinus1 = 0, sumOverPlus1 = 0;
int nextStart = 0, words = 0;
cout << "day: " << day << endl;
if (day > numDays) {
extraDay = true;
return;
}
if (start >= list.size() - 1)
return;
for (int i = start; i < list.size() - 1; i++) {
if (sumOver < wordsPerDay) {
cout << list[i] << " ";
sumUnder += list[i];
if (i + 1 < list.size())
sumOver = sumUnder + list[i + 1];
else
sumOver = sumUnder;
if (i - 1 >= 0)
sumUnderMinus1 = sumUnder - list[i - 1];
else
sumUnderMinus1 = sumUnder;
if (i + 2 < list.size())
sumOverPlus1 = sumOver + list[i + 2];
else
sumOverPlus1 = sumOver;
nextStart = i + 1;
}
if (minOverPlus1Error == sumOverPlus1 - wordsPerDay) {
sumOver = sumOverPlus1;
sumOverPlus1 = sumOverPlus1 + list[i + 3];
}
else if (minOverPlus1Error == sumOverPlus1 + list[i + 3] - wordsPerDay) {
sumOver = sumOverPlus1 + list[i + 3];
sumOverPlus1 = sumOverPlus1 + list[i + 3] + list[i + 4];
}
}
if (minOverPlus1Error == sumOver - wordsPerDay) {
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
words = sumOver;
minOverPlus1Error = INT_MAX;
}
else if (minOverPlus1Error == sumOver - wordsPerDay) {
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
words = sumOver;
minOverPlus1Error = INT_MAX;
}
else if ((wordsPerDay - sumUnder) > (sumOver - wordsPerDay)) {
cout << list[nextStart] << " ";
nextStart += 1;
words = sumOver;
}
else
words = sumUnder;
days.push_back("Day " + to_string(day) + ": Chs " + to_string(start + 1) + "-" + to_string(nextStart) + " Words: " + to_string(words));
cout << endl << "nextStart: " << nextStart << endl;
cout << "sumUnder: " << sumUnder << " error: " << wordsPerDay - sumUnder << endl;
cout << "sumOver: " << sumOver << " error: " << sumOver - wordsPerDay << endl;
cout << "sumUnderMinus1: " << sumUnderMinus1 << " error: " << wordsPerDay - sumUnderMinus1 << endl;
cout << "sumOverPlus1: " << sumOverPlus1 << " error: " << sumOverPlus1 - wordsPerDay << endl << endl;
calculate(list, days, nextStart, day + 1, numDays, wordsPerDay, extraDay, minOverPlus1Error);
if (extraDay && minOverPlus1Error > sumOverPlus1 - wordsPerDay) {
minOverPlus1Error = sumOverPlus1 - wordsPerDay;
cout << "minOverPlus1Error: " << minOverPlus1Error << endl;
}
}```
I am trying to read mesh data from a fluent mesh file. The code works perfectly till it reads node data. While reading cell data, it exits randomly by giving random negative number or what() std::bad_alloc. I am not able to understand the reason behind this behaviour. Please help me to resolve the issue. I tried printing different variables, but it works perfectly just before it exits. Here is what I have been able to put together till now
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
int str_to_int( std::string s);
double str_to_double( std::string s);
int strhex_to_int(std::string s);
std::vector<std::string> convert_string_to_vector(std::string line);
void GetDimension();
void GetNodes();
void GetCells();
void GetFaces();
void GetBcNames();
std::ifstream meshFile ;
std::string fileLine;
std::vector<std::string> lineVector;
int nDim, nNodes, nCells, nFaces;
double *nodePoints;
int *cellData, *faceData;
int main()
{
int property;
meshFile.open("test.msh", std::ifstream::in);
if (meshFile.is_open())
{
while ( !meshFile.eof() )
{
std::getline(meshFile,fileLine);
//std::cout << fileLine << "\n";
lineVector = convert_string_to_vector(fileLine);
if(lineVector.empty())
continue;
else
property = str_to_int( lineVector[0] );
//std::cout << property << "\n";
/*
for(int j=0; j < lineVector.size(); j++)
{
std::cout << lineVector[j] << "\n";
}
*/
switch(property)
{
case 0:
std::cout << "Comment Detected\n";
lineVector.clear();
break;
case 2:
GetDimension();
break;
case 10:
GetNodes();
break;
case 12:
GetCells();
break;
case 13:
GetFaces();
case 39:
GetBcNames();
default:
std::cout << "Problem with mesh file\n";
}
}
}
else std::cout << "Unable to open file";
}
void GetDimension()
{
nDim = str_to_int(lineVector[1]);
std::cout << "Problem Dimension: " << nDim << "\n";
lineVector.clear();
}
void GetNodes()
{
int nodeZoneId, startNode, endNode, nodeType;
std::string fileLine;
nodeZoneId = str_to_int(lineVector[1]);
if (nodeZoneId == 0)
{
nNodes = strhex_to_int( lineVector[3]);
std::cout << "Total Nodes = " << nNodes << "\n";
lineVector.clear();
if (nDim == 2)
nodePoints = new double[nNodes*2];
else
nodePoints = new double[nNodes*3];
}
else
{
startNode = strhex_to_int( lineVector[2]);
endNode = strhex_to_int( lineVector[3]);
nodeType = str_to_int(lineVector[4]);
std::cout << "Reading nodes from "<< startNode << " to " << endNode << " of type " << nodeType << " for zone = " << nodeZoneId << "\n";
lineVector.clear();
for( int j = startNode - 1; j < endNode; j++)
{
//std::cout << j << "\n";
std::getline(meshFile,fileLine);
if (fileLine.empty())
{
std::cout << "No Nodes found in file!" << "\n";
break;
}
//std::cout << fileLine << "\n";
lineVector = convert_string_to_vector(fileLine);
if(lineVector.empty())
j--;
else
{
if(nDim == 2)
{
//std::cout << lineVector[0] << "\t" << lineVector[1] << "\n";
nodePoints[0*nNodes + j] = str_to_double(lineVector[0]);
nodePoints[1*nNodes + j] = str_to_double(lineVector[1]);
std::cout << nodePoints[0*nNodes + j] << " " << nodePoints[1*nNodes + j] << "\n";
lineVector.clear();
}
else
{
//std::cout << lineVector[0] << "\t" << lineVector[1] << "\t" << lineVector[2] << "\n";
nodePoints[0*nNodes + j] = str_to_double(lineVector[0]);
nodePoints[1*nNodes + j] = str_to_double(lineVector[1]);
nodePoints[2*nNodes + j] = str_to_double(lineVector[2]);
std::cout << nodePoints[0*nNodes + j] << " " << nodePoints[1*nNodes + j] << " " << nodePoints[2*nNodes + j] << "\n";
lineVector.clear();
}
}
}
}
//std::getline(meshFile,fileLine);
//std::cout << fileLine << "\n";
//std::getline(meshFile,fileLine);
//std::cout << fileLine << "\n";
//lineVector.clear();
}
void GetCells()
{
int cellZoneId, startCell, endCell, cellType;
std::string fileLine;
cellZoneId = str_to_int(lineVector[1]);
//std::cout << cellZoneId << "\n";
if (cellZoneId == 0)
{
nCells = strhex_to_int(lineVector[3]);
//std::cout << "Total Cells = " << nCells << "\n";
lineVector.clear();
cellData = new int(nCells*2);
}
else
{
startCell = strhex_to_int(lineVector[2]);
endCell = strhex_to_int(lineVector[3]);
cellType = str_to_int(lineVector[5]);
std::cout << "Reading cells from "<< startCell << " to " << endCell << " of type " << cellType << " for zone = " << cellZoneId << "\n";
lineVector.clear();
if(cellType != 0)
{
for(int j = startCell - 1; j < endCell; j++)
{
cellData[0*nCells + j] = cellZoneId;
cellData[1*nCells + j] = cellType;
}
}
else
{
for(int j = startCell - 1; j < endCell; j++)
{
std::getline(meshFile,fileLine);
//std::cout << fileLine << "\n";
if (fileLine.empty())
{
//std::cout << "No Cells found in file!" << "\n";
break;
}
lineVector = convert_string_to_vector(fileLine);
if(lineVector.empty())
j--;
else
{
int k = 0;
//std::cout << lineVector.size() << "\t" << k << "\n";
while(k < lineVector.size())
{
cellData[0*nCells + j] = cellZoneId;
//std::cout << j << "\t" << lineVector[k] << "\n";
cellData[1*nCells + j] = str_to_int(lineVector[k]);
k++;
std::cout << nCells*2 << "\t" << 0*nCells + j << "\t" << 1*nCells + j << "\n";
j++;
}
lineVector.clear();
j--;
}
}
}
}
}
void GetFaces()
{
nDim = str_to_int(lineVector[1]);
lineVector.clear();
}
void GetBcNames()
{
nDim = str_to_int(lineVector[1]);
lineVector.clear();
}
std::vector<std::string> convert_string_to_vector(std::string line)
{
std::stringstream ss;
std::vector<std::string> stringVector;
stringVector.clear();
ss << line;
std::getline(ss, line);
ss.clear();
std::size_t prev = 0, pos;
//std::cout << line << "\n";
while ((pos = line.find_first_of(" ()", prev)) != std::string::npos)
{
//std::cout << prev << "\t" << pos << "\n";
if (pos > prev)
{
//std::cout << line.substr(prev,pos-prev) << "\t";
stringVector.push_back(line.substr(prev, pos-prev));
}
prev = pos+1;
}
//std::cout << "\n";
if (prev < line.length())
stringVector.push_back(line.substr(prev, std::string::npos));
/*
for(int j=0; j < stringVector.size(); j++)
{
std::cout << stringVector[j] << "\t";
}
std::cout << "\n";
*/
return stringVector;
}
int str_to_int(std::string s)
{
//std::cout << s << "\t";
std::istringstream temps(s);
int temp;
temps >> temp;
//std::cout << temp << "\n";
return temp;
}
double str_to_double(std::string s)
{
//std::cout << s << "\n";
std::istringstream temps(s);
double temp;
temps >> temp;
//std::cout << temp << "\n";
return temp;
}
int strhex_to_int(std::string s)
{
//std::cout << s << "\n";
std::stringstream temps;
temps << std::hex << s;
int temp;
temps >> temp;
//std::cout << temp << "\n";
return temp;
}
Also please indicate if there is a better way to do the same job with C++
The input file is huge so its uploaded here
https://drive.google.com/file/d/0Bz_4p6XclzrncU5BZG5MZUtNUmM/view?usp=sharing
I'm trying to find the largest 2x2 average in a matrix. I have found a person who shares a similar problem to mine however, their solution does not work.
Below is my code:
//Part B
//Finding deepest 2x2 area
int rowX, colX, ac1Row, ac1Col, ac2Row, ac2Col, ac3Row, ac3Col, ac4Row, ac4Col;
float largestArea = 0;
for(rowX = 0; rowX < dataRow - 1; rowX++){
for(colX = 0; colX < dataCol - 1; colX++){
float area = (oceanData[rowX][colX] + oceanData[rowX][colX + 1] + oceanData[rowX + 1][colX] + oceanData[rowX + 1][colX + 1]) / 4;
if(largestArea < area){
largestArea = area;
int ac1Row = rowX; int ac1Col = colX;
int ac2Row = rowX; int ac2Col = colX + 1;
int ac3Row = rowX + 1; int ac3Col = colX;
int ac4Row = rowX + 1; int ac4Col = colX + 1;
}
}
}
//Display results
cout << endl << "The deepest 2x2 area is: " << largestArea << " m" << endl;
cout << endl << "The coordinates are: (" << ac1Row << "," << ac1Col << ")" << " " << "(" << ac2Row << "," << ac2Col << ")";
cout << "(" << ac3Row << "," << ac3Col << ")" << "(" << ac4Row << "," << ac4Col << ")" << endl;
I'm using a .txt file with my data which is 6 by 6 (Data stored in oceanData, size stored in dataRow and dataCol) My output gives me the average (supposedly), however, when I try to output the coordinates I get strange numbers:
ex.
The coordinates are: (4356788,0),(0,0),(0,0),(8,0)
Anyone see where my problem is?
Thanks!
You are redefining the variables on each loop:
int ac1Row = rowX; int ac1Col = colX;
But you don't even need all 8 variables, you can save only the coordinates of a single corner and calculate the others.
Consider this
int acRow, acCol;
float largestArea = 0;
for(int rowX = 0; rowX < dataRow - 1; rowX++){
for(int colX = 0; colX < dataCol - 1; colX++){
float area = (oceanData[rowX][colX] + oceanData[rowX][colX + 1] + oceanData[rowX + 1][colX] + oceanData[rowX + 1][colX + 1]) / 4;
if(largestArea < area){
largestArea = area;
acRow = rowX;
acCol = colX;
}
}
}
cout << endl << "The deepest 2x2 area is: " << largestArea << " m" << endl;
cout << endl << "The coordinates are: (" << acRow << "," << acCol << ")" << " " << "(" << acRow << "," << acCol + 1 << ")";
cout << "(" << acRow + 1 << "," << acCol << ")" << "(" << acRow + 1 << "," << acCol + 1 << ")" << endl;
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;
}
}
I study C ++ and try to create the first game. Here's the code:
#include <iostream>
#include <string>
using namespace std;
void info () {
int LVL = 1;
int money = 1000;
int EXP = 0;
int work = 200;
int learn = 15;
int k = 0;
}
void menu ()
{
info ();
char menu_items;
cout << "Choose action: " << "\n" << "1. Work" << "\n" << "2. Learn" << endl;
cin >> k;
if (k == 1){
int money = money + work;
cout << "U worked (+ "<< money << " dollars)" << "\n" << endl;
} if (k == 2) {
int EXP = EXP + learn;
cout << "U learned (+ " << EXP << " EXP)" << "\n" << endl;
} else {
cout << "ERROR" << endl;
}
}
int main()
{
info ();
while (LVL == 10) {
cout << "End game!";
}
while (LVL != 10) {
cout << "Your data: " << "\n" << "Money: " << money << "\n" << "EXP: " << EXP << "\n" << "LVL: " << LVL << "\n" << endl;
menu ();
}
}
Please correct the following:
1) The cyclic output data after rewrite
2) Proper cycle add money and experience when choosing one of the following actions
Info should probably be a class or struct. You only want to instantiate it once, and persist the values over your calls.
One option might be:
#include <iostream>
#include <string>
using namespace std;
struct info {
int lvl = 1;
int money = 1000;
int exp = 0;
const int work = 200;
const int learn = 15;
};
int main()
{
info i;
string k;
while (i.lvl < 10)
{
cout << "Your data: " << "\n" << "Money: " << i.money << "\n" << "EXP: " << i.exp << "\n" << "LVL: " << i.lvl << endl;
cout << "Choose action: " << "\n" << "1. Work" << "\n" << "2. Learn" << endl;
cin >> k;
if (k == "1")
{
i.money += i.work;
cout << "You worked (+ " << i.work << " dollars, now " << i.money << ")" << endl;
}
else if (k == "2")
{
i.exp += i.learn;
cout << "You learned (+ " << i.learn << " EXP, now " << i.exp << ")" << endl;
}
else
{
cout << "ERROR" << endl;
}
}
cout << "You won!" << endl;
}
#include <iostream>
#include <string>
using namespace std;
void menu()
{
int money = 1000;
int EXP = 0;
int work = 200;
int learn = 15;
int k = 0;
cout << "Choose action: \n 1. Work \n 2. Learn "<< endl;
cin >> k;
if (k == 1){
money =money + work;
cout << "U worked (+ " << money << " dollars)" << "\n" << endl;
} if (k == 2) {
EXP = EXP + learn;
cout << "U learned (+ " << EXP << " EXP)" << "\n" << endl;
}
else {
cout << "ERROR" << endl;
}
}
int main()
{
int money = 1000;
int LVL = 1;
int EXP = 0;
while (LVL == 10) {
`cout << "End game!"; `
}
while (LVL != 10) {
cout << "Your data: " << "\n" << "Money: " << money << "\n" << "EXP: " << EXP << "\n" << "LVL: " << LVL << "\n" << endl;
menu();
}
return 0;
}