PLEASE NEED HELP: Sorting Dynamic Array while reading file

I have an assignment in which I have to read from a file called ("random.txt") output the total and copy the file into an array dynamically. Then sort the values in the file.

Up until line 20 my programs runs fine and outputs my total values as well as all the numbers in file.

Line 21 onward also runs but then it doesn't output the total I had in line 20 when I run it and it also doesn't display the values in order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 #include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
  ifstream fin;
  int n=0;
  double temp;
  fin.open("random.txt");
  fin>>temp;
  while(fin)
  {
      n++;
      fin>>temp;
      cout<<temp<<endl;
  }
  cout<<"Total:"<<n<<endl;
  fin.close();
  fin.open("random.txt");
  double *A;
  A=new double[n];
  for (int i=0;i<n-1;i++)
    for (int j=i;j<n;j++)
    if (A[i]>A[j])
    {
      int temp=A[i];
      A[i]=A[j];
      A[j]=temp;
    }
  for (int i=0;i<n;i++)
    {
      while(fin)
      {
          n++;
          cout<<"Array:"<<A[i]<<endl;
          fin>>A[i];
      }

  }
  fin.close();
}
Last edited on
On line 23 you create a dynamic array. The values in this dynamic array reflect whatever junk occupied the memory when it was allocated. On line 24 to 31 you sort these indeterminate values.

The for loop on line 32 appears to be an attempt to read values into that dynamic array. Why is there a while loop inside the for loop? Why is n being increased on line 36? Why do you output the value contained in the array and then overwrite it with a value from the file?
The while loop inside my for loop was an attempt to read the values. I increased n because I thought I should do the same as I did in the beginning on lines 13-18 to read from the file. For lines 37 and 38 are you asking that I should have switched them? I know I have a lot of errors, I'm very new to c++ so I'm still trying to learn. To be quite honest I don't know what I'm doing starting from line 32. I understand that I sorted my array from 24-31, but I don't know how to read my file into my array or how to format it.
Last edited on
Topic archived. No new replies allowed.