I'm working on a code that reads a file containing the "course" of a racetrack and needs to determine how tall and wide the course is first. A sample course looks like such:
xxxxXxxxxXxxxxXxxxxXxxxxXxxxxX
xxxxxx xxxxx xxx xx
xxxxx xxx xx x
xx xx x x x
X xx x x x
x xx x x
x xxxxxxxxxxxxxx x x
x xxxxxxxxxxxxxxxxxxxxx x
xFFFF x xxxxxxxxxxxxxx x
XFFFF x xxxxxxxx x
x x 1 x
xxxxxxx 2 xxx x
xxxxxx 3 x x
x x
Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Now because arrays require constant values at compile-time, and I cannot provide that, I attempted to Dynamically allocate the array to memory once the height and width values were retrieved. In sum, my code looks as such:
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
struct Level {
int HEIGHT;
int WIDTH;
};
vector<Level> getRowCol(istream& fin) {
vector<Level> level;
fin.seekg(0, fin.end);
int fileSize = fin.tellg();
fin.seekg(0, fin.beg);
string s;
if (getline(fin, s)) {
Level l;
l.WIDTH = s.size();
l.HEIGHT = fileSize / (l.WIDTH + 1);
level.push_back(l);
}
return level;
}
void readCourse(int& cols, int& rows, istream& fin) {
char** level = new char*[rows];
for (int i = 0; i < cols; i++) {
level[i] = new char[cols];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
level[i][j] = 0;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
fin.get(level[i][j]);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << level[i][j];
}
}
}
int main(int argc, char** argv) {
vector<Level> course;
ifstream fin(argv[1]);
course = getRowCol(fin);
cout << course[0].WIDTH << " columns" << endl;
cout << course[0].HEIGHT << " rows" << endl;
readCourse(course[0].WIDTH, course[0].HEIGHT, fin);
return 0;
}
The output of this code when passed the file via command line looks like:
31 columns
14 rows
xxxxxx xxxxx xxx xx
xxxxx xxx xx x
xx xx x x x
X xx x x x
x xx x x
x xxxxxxxxxxxxxx x x
x xxxxxxxxxxxxxxxxxxxxx x
xFFFF x xxxxxxxxxxxxxx x
XFFFF x xxxxxxxx x
x x 1 x
xxxxxxx 2 xxx x
xxxxxx 3 x x
x x
Xxxxxxxxxxxxxxxxxx
There now appear to be gaps. These gaps do not appear if const int
values are declared prior to compile time. However I cannot think of another way to have the array build with unknown values until the script is run short of using Dynamic allocation.
Is there another, or a better, way to accomplish this?