Since your input file is line oriented, you should use getline (the equivalent of C ++ or C fgets) to read the line, and then istringstream to parse the line into integers. And since you do not know a priori size, you must use vectors and sequentially control that all rows are the same size and the number of rows is the same as the number of columns.
Last but not least, you should check eof immediately after reading, and not at the beginning of the loop.
The code becomes:
#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> using namespace std; int main() { fstream f; int i=0, j=0, n=0; string line; vector<vector<int>> a; f.open("array.txt", ios::in); for(;;) { std::getline(f, line); if (! f) break; // test eof after read a.push_back(vector<int>()); std::istringstream fline(line); j = 0; for(;;) { int val; fline >> val; if (!fline) break; a[i].push_back(val); j++; } i++; if (n == 0) n = j; else if (n != j) { cerr << "Error line " << i << " - " << j << " values instead of " << n << endl; } } if (i != n) { cerr << "Error " << i << " lines instead of " << n << endl; } for(vector<vector<int>>::const_iterator it = a.begin(); it != a.end(); it++) { for (vector<int>::const_iterator jt = it->begin(); jt != it->end(); jt++) { cout << " " << *jt; } cout << endl; } return 0; }
source share