I am working on my C++ (File Handling) Project but got stuck on a point
Here is my .txt file
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56
I have to display the top 5 movies with respect to NoOfPeopleLiked Just like that:
Sample Output
1, The Shawshank Redemption, 77
2, The Lord of the Rings: The Fellowship of the Ring, 56
3, The Dark Knight, 55
4, 12 Angry Men, 44
5, Into The Wild, 36
so I have to do sorting and this is what I have done so far
void topFive()
{
Movies v[20]; //class object array
fstream top; //for reading
top.open("movies.txt");
for (int h = 0; h < 10; h++) // reading from txt file
{
top >> v[h].serial >> v[h].movieName >> v[h].liked;
}
// run loops two times: one for walking throught the array
// and the other for comparison
for (int step = 0; step < 5; ++step)
{
for (int i = 0; i < 5 ; ++i)
{
// To sort in descending order, change > to < in this line.
if (v[i].liked > v[i + 1].liked)
{
// swap if greater is at the rear position
int temp = v[i].liked;
v[i].liked = v[i + 1].liked;
v[i + 1].liked = temp;
}
}
}
// to print the array
for (int i = 0; i < 5; ++i)
{
cout << v[i].serial << ", " << v[i].movieName << ", " << v[i].liked << endl;
}
}
To be Honest I did not know how to do it perfectly I am stucked with this problem for about 6-7 hours and still can't make any logic. I hope you guyz can help me and guide me better. Thanks in advance :)