I wish to read a text file such as
4
2
3
4 3
2 1
5 4
8 4
The first line being the first dimension of a 2D array and the second line being the second dimension of a 2D array and the third line being a value. Upon reading and storing the first three values into the variables n,m,k i would like to initialize the 2D int array int x[n][m].
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
using namespace std;
int n,m,k;
int main()
{
ifstream File;
File.open("text.txt");
if (File.fail()) {
cout << "error opening file";
}
while (!File.eof())
{
File >> n;
File >> m;
File >> k;
int x[n][m];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
File >> x[i][j];
}
}
}
return 0;
}
However, I cannot initialize the array as it appears the expression n and m do not have constant values. If i were to set the variables to const int n,m,k, i would not be able to read them from the file using >>. How can i read the array sizing values, use them to create the array, and then store the values in them?
edit:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <math.h>
using namespace std;
std::vector < std::vector <int>> x;
int n,m,k;
int main()
{
ifstream File;
File.open("test.txt");
if (File.fail()) {
cout << "error opening file";
}
while (!File.eof())
{
File >> n;
File >> m;
File >> k;
for (int i = 0; i < n; i++) {
vector <int> row;
for (int j = 0; j < m; j++) {
int readFromFile = 0;
File >> readFromFile;
row.push_back(readFromFile);
}
x.push_back(row);
}
}
cout << n;
cout << "\n";
cout << m;
cout << "\n";
cout << k;
cout << "\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << x[i][j];
cout << " ";
}
cout << "\n";
}
return 0;
}