Your problem is not with the dynamic array, it is creating an array with the required length.
If you open this in a debugger and go through line by line you will see that in
1 2 3 4 5 6 7 8
|
for (int i=0;i<n;i++)
{
while(fin)
{
cout<<A[i];
fin>>A[i];
}
}
|
The while loop is loading the file into A[], therefore the for loop is not needed. But if you remove the while loop and use the for loop, it will also work because you are loading the correct amount of items. You can pick either of these and they will work:
1 2 3 4 5
|
for (int i=0;i<n;i++)
{
cout<<A[i];
fin>>A[i];
}
|
1 2 3 4 5 6 7
|
int i;
while(fin)
{
cout<<A[i];
fin>>A[i];
i++;
}
|
One more thing, because you are using new and creating a dynamic array, you must call delete or you will get a memory leak.
At the end of main() put this line
delete A;
If your program is crashing on line 22, you can try replacing
1 2
|
fin.close();
fin.open("data.txt");
|
with
1 2
|
fin.clear(); //clears end of file bit
fin.seekg(0, ios::beg); //goes back to the start of the file
|
This may help because I have noticed in some OS, closing a file and opening it again too quickly will fail. I have noticed this in windows 8.