I would like to get an int from a file and use that as the number of elements when declaring an array. However using the code below it seems to want const number of elements. How can I go about this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<fstream>
usingnamespace std;
int main(){
ifstream inputFile;
inputFile.open("input_data.txt");
int rows;
inputFile >> rows;
int arr[rows]; //"rows" is giving error for not being const
return 0;
}
The reason the method your trying won't work and requires const is because the computer allocates the space required at compile time (i.e. it needs to know exactly how much memory it will need). Trying to allocate that memory after reading in the file means it can be a variable amount.
That said, your solution would be to dynamically allocate memory by using the new operator.
1 2 3
int rows;
inputFile >> rows;
int arr = newint[ rows ];