#include <iostream>
#include <string>
#include <fstream> // to read file
#include <algorithm> // to use sort
usingnamespace std;
constint SIZE = 100;
struct Movie // movie information
{
string name[SIZE];
int year;
double price;
};
int main()
{
cout << "The movies that we have on the list are" << endl;
cout << "-----------------" << endl;
ifstream listfile;
listfile.open("Movie.txt");
Movie list; // struct object
if (listfile.is_open())
{
string name;
string temp;
while (getline(listfile, name))
{
cout << name << endl;
}
}
else
cout << "unable to read file" << endl;
listfile.close();
system ("pause");
return 0;
}
i am trying to read the file in alphabetical order but i wanted to use the sort function i found online but i can't understand it can someone explain it to me please.
sort (name.begin(), name.end(), myobject);
for example the text reads names of movies that are out of order by title how would you use the sort function.
Line 12: Your dimension is in the wrong place. A movie doesn't have 100 names. By using a vector, you don't need to explicitly dimension list.
Line 37-41: You're reading name from the file, but not putting it anywhere. Need to know the format of the file in order to know how to read year and price.
#include <iostream>
#include <string>
#include <fstream> // to read file
#include <algorithm> // to use sort
#include <vector>
usingnamespace std;
struct Movie // movie information
{ string name;
int year;
double price;
};
bool compare_movies (const Movie & a, const Movie & b)
{ return a.name < b.name;
}
int main()
{ vector<Movie> list; // Movies are stored here
string name;
int count = 0;
cout << "The movies that we have on the list are" << endl;
cout << "-----------------" << endl;
ifstream listfile;
listfile.open("Movie.txt");
if (! listfile.is_open())
{ cout << "Could not open movie.txt" << endl;
return 1;
}
while (getline(listfile, name))
{ Movie temp;
temp.name = name;
list.push_back (temp);
}
sort (list.begin(), list.end(), compare_movies); // Sort the movies read
cout << "The movies (in alphabetical order) are: " << endl;
for (unsigned i=0; i<list.size(); i++)
cout << list[i].name << endl;
system ("pause");
return 0;
}
@Thomas1965 I never messed with vectors before need to look into it and also is that the only way I put 100 for the amount of movies that the program can read, i am very new to c++, did I do it incorrectly?
@AbstractionAnon thanks for the help but, question what does the push_back do on line 35. and for the sort on line 37 i know that it reads the beginning to the end but what about the third item in the sort function what does that read?
what about the third item in the sort function what does that read?
The third argument is a compare function (line 14). Since Movie is a custom type, we have to tell sort how to compare two Movie entries. See the comp argument on the second prototype here: http://www.cplusplus.com/reference/algorithm/sort/