I'm creating a program that reads text files, each with a priority and message, and then prints them in the correct order. Files with higher priority are printed first, and if they have the same priority, the ones that were entered in first are printed first. My code compiles fine, but if more than 3 text files are entered, I get a Segmentation fault. It also has a problem sorting by priority. Is there a way to fix this without significantly changing my code?
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
/* ----------------------- Package Class ----------------------- */
class package
{
public:
int priority;
int order;
string message;
};
/* ----------------------- Main Program ----------------------- */
int main()
{
/* ----------------------- The Variables ----------------------- */
int amount;
package temp;
package *packages;
string fileName;
ifstream fin;
/* ----------------------- Opening the Files ----------------------- */
cout << "\nEnter the amount of packages you want entered: " << endl;
cin >> amount;
packages = new package[amount];
if (packages == 0)
cout << "Memory Cannot Be Allocated";
cout << "\nEnter the names of the packages one by one:" << endl;
for (int i=0; i<amount; i++)
{
cout << "Package " << i+1 << ": ";
cin >> fileName;
fin.open(fileName.data(), ios::in);
assert( fin.is_open() );
fin >> packages[i].priority;
getline(fin, packages[i].message);
packages[i].order = i+1;
fin.close();
}
/* ----------------------- Sorting the Packages ----------------------- */
for (int i=1; i<amount-1; i++)
{
for (int j=0; j=amount-i; j++)
{
if (packages[j].priority > packages[j+1].priority)
{
packages[j] = temp;
packages[j] = packages[j+1];
packages[j+1] = temp;
}
if (packages[j].priority == packages[j+1].priority)
{
if (packages[j].order > packages[j+1].order)
{
packages[j] = temp;
packages[j] = packages[j+1];
packages[j+1] = temp;
}
}
}
}
/* ----------------------- Printing the Files ----------------------- */
cout << "The Packages:";
for (int i=0; i<amount; i++)
{
cout << "\n\n" << "Priority: "<< packages[i].priority << "\nOrder: " << packages[i].order << "\n" << packages[i].message;
}
cout << endl << endl;
delete[] packages;
return 0;
}
Here is an example text file: (the first character is the priority, 1 being highest)
Code:
1This program is awesome
Thanks so much for the help!