I have an array with a very large size (let's say 50x50 for the sake of argument).
I need to input all of the values manually into this array but I can't figure out the best way to do it (there is no pattern to the values in the array). I wouldn't mind doing column by column but having to do each and every cell will take forever! Is there an easier way? Something like I have below?
int table[50][50];
table[0][]={1,20, 40, 100, 2,25,42, 5600... 50};
table[1][]={1,2,3,4,5...50};
You can export it to a CSV and then read it in at runtime, then. That much data shouldn't be hard coded into the program's source code, nor should it be on the stack.
Awesome... One last question (or two)
Does that csv need to be stored in any certain location? I've tried putting it in every folder but can't seem to get it to work.
When I attempt to view one of the values in table I am getting -842150451 as the value.
I've been messing with this for a few days and still can't get it to read in all the values. My code is as seen below. For some reason the only value working properly is table[0][0].
1 2 3 4 5 6 7 8 9 10
std::ifstream infile("strat.csv");
int **table = newint*[37];
for(unsigned r = 0; r < 37; ++r)
{
table[r] = newint[23];
for(unsigned c = 0; c < 23; ++c)
{
infile >> table[r][c];
}
}
There was one part that was omitted in LB's code. If you open up a csv file in a text editor (notepad, vi, ...) then you'll notice that the values are are seperated by a comma. I don't think this code considers that.
std::ifstream infile("strat.csv");
int **table = newint*[37];
for (int r = 0; r < 37; ++r)
{
// get a whole line
std::string row;
std::getline(infile, row);
// remove the commas, replace with spaces
for (int i = 0; i < row.size(); ++i)
if (row[i] == ',')
row[i] = ' ';
// stick the row back in a stream so we can extract ints easily
std::stringstream row_stream(row);
// Stick everything in the table
table[r] = newint[23];
for (int c = 0; c < 23; ++c)
row_stream>> table[r][c];
}
If your csv is of an unknown size, use vectors. I'll post an example in a bit.Edit: Here it is:
std::ifstream infile("strat.csv");
std::vector< std::vector<int> > csv_data;
std::string row;
while (std::getline(infile,row) )
{
// remove the commas, replace with spaces
for (int i = 0; i < row.size(); ++i)
if (row[i] == ',')
row[i] = ' ';
// stick the row back in a stream so we can extract ints easily
std::stringstream row_stream(row);
// define a row
std::vector<int> row_data;
int data;
// Extract values from the stream and set it to the row vector
while ( row_stream.good() )
{
row >> data;
row_data.push_back(data);
}
// Put the row in the main object
csv_data.push_back(row_data);
}
// To access the data:
for (int r = 0; r < csv_data.size(); ++r)
{
for (int c = 0; c < csv_data[r].size(); ++c)
std::cout << csv_data[r][c] << ' ';
std::cout << std::endl;
}