storing a file to array and sorting

output is wrong suppose to sort the file


void main()
{
vector<user> userA;

ifstream infile;
infile.open("UserID.txt");
if(infile.fail()){
cerr<<"Fail on opening file\n";
}
while(infile.good()){
user *uptr=new user;
infile>>uptr->ID>>uptr->lname>>uptr->fname>>uptr->pass>>uptr->Resourcel>>uptr->usedR;
userA.push_back(*uptr);
delete uptr;
}
int *comp=new int[userA.size()];
for(int j=0;j<userA.size()-1;j++){
comp[j]=j;
}
for(j=0;j<userA.size()-1;j++){
cout<<comp[j]<<endl;
}
int best, temp;
for (int i = 0; i < userA.size()-1; i++)
{
best = i;
for (int j = i+1; j < userA.size(); j++)
if (userA[best].usedR < userA[j].usedR)
best = j;

if (i != best)
{
temp=comp[i];
comp[i]=best;
comp[best]=temp;
}
}
for(j=0;j<userA.size()-1;j++){
cout<<comp[j]<<endl;
}
for(int h=0;h<userA.size()-1;h++){
cout<<userA[comp[h]].usedR<<endl;
}
delete comp;
infile.close();
}
Last edited on
change compare from userA[best].usedR > userA[j].usedR to

userA[best].usedR < userA[j].usedR

and put swap via temp variable within braces.


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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const int MAX_NAME_LEN = 30;


struct user
{
   int      ID;
   char     lname[MAX_NAME_LEN];
   char     fname[MAX_NAME_LEN];
   char     pass[MAX_NAME_LEN];
   int      Resourcel;
   double   usedR;
};
   


void main()
{
   vector<user> userA;

   ifstream infile;
   infile.open("UserID.txt");
   if(infile.fail()){
      cerr<<"Fail on opening file\n";
   }
   while(infile.good()){
      user *uptr=new user;
      infile>>uptr->ID>>uptr->lname>>uptr->fname>>uptr->pass>>uptr->Resourcel>>uptr->usedR;
      userA.push_back(*uptr);
      delete uptr;
   }
   int *comp=new int[userA.size()];
   for(int j=0;j<userA.size()-1;j++){
      comp[j]=j;
   }
   for(j=0;j<userA.size()-1;j++){
      cout<<comp[j]<<endl;
   }
   int best, temp;
   for (int i = 0; i < userA.size()-1; i++)
   {
      best = i;
      for (int j = i+1; j < userA.size(); j++)
         if (userA[best].usedR < userA[j].usedR)
            best = j;

      if (i != best)
      {
         temp=comp[i];
         comp[i]=best;
         comp[best]=temp;
      }
   }
   for(j=0;j<userA.size()-1;j++){
      cout<<comp[j]<<endl;
   }
   for(int h=0;h<userA.size()-1;h++){
      cout<<userA[comp[h]].usedR<<endl;
   }
   delete comp;
   infile.close();
}
Topic archived. No new replies allowed.