Can anyone help me out here? When I run the program it runs and everything is right but when I upload it onto the grader (ZyBooks) it is giving me this error: "Unhandled exception: Range error: 2" for the function createMatrix. The file that was read from contains coordinate points in (x, y, z) format and is read into a vector of type Point and then translated into a matrix (2D vector).
The coordinates.txt contains: (1,2,3) (4,5,6) (7,8,9) (10,11,12) (13,14,15)
Thank you, I have posted my code below.
#include "std_lib_facilities.h"
struct Point {
double x;
double y;
double z;
};
istream& operator>>(istream& is, Point& p) {
char dummy;
is >> dummy;
is >> p.x;
is >> dummy;
is >> p.y;
is >> dummy;
is >> p.z;
is >> dummy;
return is;
}
ostream& operator<<(ostream& os, const Point& p) {
return os << "(" << p.x << "," << p.y << "," << p.z << ")";
}
void createMatrix(const vector<Point>& v1, vector<vector<double> >& v2) {
// Set row for x
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 5; j++) {
v2[i][j] = v1[j].x;
}
}
// Set row for y
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 5; j++) {
v2[i + 1][j] = v1[j].y;
}
}
// Set row for z
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 5; j++) {
v2[i + 2][j] = v1[j].z;
}
}
}
int main() {
// Open the file and read it into a vector of Points
// Declare a 2D vector of doubles with 3 rows and n columns,
// where n is the total number of Points read
// Pass the two vectors into createMatrix
// Output the matrix vector to a file named "coordinateMatrix.txt"
ifstream ifs;
// Open the input file
ifs.open("coordinates.txt");
Point p;
vector<Point> originalPoints;
int n = 0;
// Write from file into vector of type Point
for (int i = 0; i < 5; i++) {
ifs >> p;
originalPoints.push_back(p);
n++;
}
// Declare new 2D vector
vector<vector<double> > matrix(3, vector<double>(n));
// Create matrix with vector of original points
// x x x x x
// y y y y y
// z z z z z
createMatrix(originalPoints, matrix);
// Close the input file
ifs.close();
ofstream ofs;
// Open the output file
ofs.open("coordinateMatrix.txt");
// Write the matrix into output file
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
ofs << matrix[i][j] << " ";
}
ofs << endl;
}
// Close the output file
ofs.close();
}
UPDATE: Thanks to Thomas, I changed my function to the code below and it worked!
void createMatrix(const vector<Point>& v1, vector<vector<double> >& v2) {
// Set row for x
for (long unsigned int i = 0; i < 1; i++) {
for (long unsigned int j = 0; j < v1.size(); j++) {
v2[i][j] = v1[j].x;
}
}
// Set row for y
for (long unsigned int i = 0; i < 1; i++) {
for (long unsigned int j = 0; j < v1.size(); j++) {
v2[i + 1][j] = v1[j].y;
}
}
// Set row for z
for (long unsigned int i = 0; i < 1; i++) {
for (long unsigned int j = 0; j < v1.size(); j++) {
v2[i + 2][j] = v1[j].z;
}
}
}