You are making things much more difficult on yourself by using a fixed array instead of a vector of vector<int> for your 2D array. Additionally, for parsing a .csv file, reading each complete line, and then creating a stringstream from the line and parsing with getline using ',' terminator and then using stoi to convert the field to integer value (C++11) makes the process quite simple.
For example, taking the filename to read as the first argument to the program, you could implement the above as:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main (int argc, char **argv) {
string line; /* string to hold each line */
vector<vector<int>> array; /* vector of vector<int> for 2d array */
if (argc < 2) { /* validate at least 1 argument given */
cerr << "error: insufficient input.\n"
"usage: " << argv[0] << " filename\n";
return 1;
}
ifstream f (argv[1]); /* open file */
if (!f.is_open()) { /* validate file open for reading */
perror (("error while opening file " + string(argv[1])).c_str());
return 1;
}
while (getline (f, line)) { /* read each line */
string val; /* string to hold value */
vector<int> row; /* vector for row of values */
stringstream s (line); /* stringstream to parse csv */
while (getline (s, val, ',')) /* for each value */
row.push_back (stoi(val)); /* convert to int, add to row */
array.push_back (row); /* add row to array */
}
f.close();
cout << "complete array\n\n";
for (auto& row : array) { /* iterate over rows */
for (auto& val : row) /* iterate over vals */
cout << val << " "; /* output value */
cout << "\n"; /* tidy up with '\n' */
}
return 0;
}
(note: the automatic memory management provided by string and vector will allow you to read an array of any size (up to the limits of your virtual memory) without knowing the number of fields or rows beforehand. You can add simple counters for validating each row contains an equal number of values, etc...)
Example Input File
$ cat file.txt
1,1,1
1,2,3
3,1,3
Example Use/Output
$ ./bin/iostream_sstream_csv_stoi file.txt
complete array
1 1 1
1 2 3
3 1 3
Look things over and let me know if you have further questions.
while (myFile.good()). Check the return value of your actual input functions to detect an error or no more data. stackoverflow.com/questions/5605125/…