Data file formatting - Greatest to Least
Sep 27, 2012 at 3:50pm UTC
I have a Trivial Pursuit type program. The following program is the program I use as a leaderboard.. so when it runs it pulls the scores of all of those users that have played and shows them on the screen. How would I order the scores in greatest to least?
for example, running the program now will print something along the lines of
BMT 9
JAS 3
FKE 6
TLO 4
while I'd like it to print
BMT 9
FKE 6
TLO 4
JAS 3
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
//Brandon Thomas
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string name;
int num, n=1;
ifstream infile;
infile.open("H:\\files\\score.txt" );
string Name[50];
int Num[50];
infile >> name;
infile >> num;
while (!infile.eof())
{
infile >> Name[n];
infile >> Num[n];
cout << Name[n] << " \t" << Num[n] << endl;
n++;
}
system("PAUSE" );
return 0;
}
Last edited on Sep 27, 2012 at 4:03pm UTC
Sep 27, 2012 at 4:24pm UTC
I figured it out, I hope this code helps whoever needs it
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
//Brandon Thomas
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
string name;
int num, n=0;
ifstream infile;
infile.open("H:\\files\\score.txt" );
string Name[50];
int Num[50];
infile >> name;
infile >> num;
while (!infile.eof())
{
infile >> Name[n];
infile >> Num[n];
cout << setfill(' ' ) << setw(5) << Name[n] << setw(5)<<Num[n]<<endl;
n++;
}
int temp;
string tempName;
for (int y=0; y < n; y++)
{
for (int k =0; k < n -1-y; k++)
{
if (Num[k]<Num[k+1])
{
temp = Num[k];
Num[k] = Num[k+1];
Num[k+1] = temp;
tempName = Name[k];
Name[k] = Name[k+1];
Name[k+1] = tempName;
}
}
}
cout << endl<<endl;
cout << "Sorted Array" << endl<<endl;
for (int i = 0; i < n; i++)
{
cout << setfill(' ' ) << setw(5) << Name[i] << setw(5)<<Num[i]<<endl;
}
system("PAUSE" );
return 0;
}
Sep 27, 2012 at 4:26pm UTC
The easiest solution is to pack all the names and numbers into a struct like this:
1 2 3 4 5 6
struct score {
string name;
int num;
score(string n, int x) : name(n), num(x) {}
};
Then you put all the information in a random-access container like vector:
1 2 3 4 5
vector<score> data;
data.push_back(score("Name1" , num1));
data.push_back(score("Name2" , num2));
...
Now you just need to sort this vector using the std::sort algorithm you get with the <algorithm> header. (see
http://www.cplusplus.com/reference/algorithm/sort/)
Topic archived. No new replies allowed.