Number of array elements from input file?

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>
using namespace 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;
}


Thank you.
Number of automatic lifetime array elements should be compile-time constant.
In your case you can either allocate array dynamically:
1
2
3
4
5
int rows;
inputFile >> rows;
int* arr = new int[rows];
//Use array here
delete[] arr; //Do not forget to clean after use. 
Or use vector which should be always considered first instead of arrays.
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 = new int[ rows ];

http://www.cplusplus.com/reference/new/operator%20new%5B%5D/
Last edited on
Ah okay got it. Thank you MiiNiPaa and Keene.
Topic archived. No new replies allowed.