I have a text file that is in the format of a rectangle, with various characters. What I want to do is to read that text file into a 2d array, like a grid. For an example, if the text file was something like this
15681
28515
32414
12451
If I was to call grid[3][2], with [x] and [y] parameters respectively, the value of grid[3][2] would be 5, which is found in row 3, column 2.
I originally tried doing this by declaring the grid as a char array
array[x][y]
Where I had determined the values of x and y (how many lines were in the file, how many columns were in the file) by reading how many lines were in the file, and how many characters were in a line. I know that my code is likely superfluous and I could cut down on the amount of work by implementing a vector array, but I'm not sure how I would go about doing that.
int x = 0; int y = 0;
grid[x][y] = whatever the current character in the file is;
every time a character is stored, x++
when a newline is encountered, y++;
I would think that would properly save all the values to the grid, but I don't know the syntax on how to do that.
Another idea I thought about was to maybe have an array of Points, a class I would create that would contain an X value and a Y value, though I've no idea how I would actually implement it.
I've got no idea about how to go about doing the first option syntax wise, and I've got no clue on how to even start with my second option. Can anyone give me some hints or redirect me to any information that would help teach me?
EDIT: code that crashes
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
std::vector<std::string> grid;
std::string line;
int main(int argc, char** argv)
{
std::string current_exec_name = argv[0];
std::string filename;
if (argc > 1){
filename = argv[1];
}
cout << filename;
ifstream infile(filename.c_str());
while (infile.good())
{
grid.push_back(line);
}
grid[2][1] = 4;
//the line above
}
I've tried doing the following codes where the program crashes
grid[2][1] = 4;
grid[2][1] = "4";
grid[2] = 4;
grid[2] = "4";
The program builds, but crashes when it runs.
grid[3][2]should actually return 4 (assuming we start counting the indices from 0). Right?