I\'m writing this program that takes the first entry of data from a text file, t
ID: 3822348 • Letter: I
Question
I'm writing this program that takes the first entry of data from a text file, the first value of the text file should be used to deterimine the size of the array chicago[], but the compiler keeps saying that "expression must have a constant value". The first data point in the text file is 9, which I tried to assign to a constant int value, but for some reason it's not working. Any solutions?
This is what the text file looks like:
9
101
112
115
110
103
120
105
100
119
The program so far:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ()
{
ifstream fin;
const int test = 10;
int index = 0;
int file_size;
int product_number;
fin.open ("chicago.txt");
fin >> file_size;
const int filesize = file_size;
cout << file_size;
cout << " " << filesize;
int chicago[filesize]; - "expression must have a constant value"
//fin >> product_number;
//while (!fin.fail())
//{
//chicago[index] = product_number;
//index++;
//}
system ("pause");
return 0;
}
Explanation / Answer
Hi
I have fixed the issue and highlighted the code changes below
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ()
{
ifstream fin;
const int test = 10;
int index = 0;
int file_size;
int product_number;
fin.open ("chicago.txt");
fin >> file_size;
const int filesize = file_size;
cout << file_size;
int *chicago = new int [filesize]; // - "expression must have a constant value"
while (!fin.fail())
{
fin >> product_number;
chicago[index] = product_number;
index++;
}
cout<<"Array elements are: "<<endl;
for(int i=0; i<file_size; i++){
cout<<chicago[i]<<" ";
}
cout<<endl;
delete[] chicago;
fin.close();
system ("pause");
return 0;
}