How to read the 2nd array from a file without knowing its length in C ++?

As in the title, I am trying to read an unknown number of integers from a file and put them in a 2d array.

#include <iostream> #include <fstream> using namespace std; int main() { fstream f;int i,j,n,a[20][20];char ch; i=0;j=0;n=0; f.open("array.txt", ios::in); while(!f.eof()) { i++; n++; do { f>>a[i][j]; j++; f>>ch; } while(ch!='\n'); } for(i=1;i<=n;i++) { for(j=1;j<=n;j++) cout<<a[i][j]<<endl; cout<<endl; } return 0; 

}

and my file "array.txt":

 1 1 1 2 2 2 3 3 3 

After compiling the program, it prints this

enter image description here

+5
source share
3 answers

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; } 
+3
source

You might want to examine the vector to have a dynamic array.

+1
source

Try:

 #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; int main() { fstream f; int i, j, n, a[20][20]; string buf; i = 0; j = 0; n = 0; f.open("array.txt", ios::in); while (1) { getline(f, buf); if (f.eof()) break; stringstream buf_stream(buf); j = 0; do { buf_stream >> a[i][j]; j++; } while (!buf_stream.eof()); i++; n++; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << a[i][j] << " "; cout << endl; } return 0; } 

Also, if you really want to read arbitrarily large arrays, then you should use std::vector or some other container, not raw arrays.

0
source

Source: https://habr.com/ru/post/1238176/


All Articles