Best Selling Items Program/ Need Help finding the Top and second top selling items

I am Having trouble finding the 1st and 2nd top selling items and i just need it to print in the console... can someone help me out with that i think the problem is in lines 58-64


#include <iostream>
#include <string>
#include<fstream>

using namespace std;

struct Product {
int productNumber;
string productName;
double unitPrice;
int unitsSold;
};

int main() {
struct Product p[100];
int i = 0, j;
int totalRevenue;

ifstream infile;
infile.open("sales.txt");

while (!infile.eof()) {
infile >> p[i].productNumber;
infile >> p[i].productName;
infile >> p[i].unitPrice;
infile >> p[i].unitsSold;
i++;
}
totalRevenue = i;

for (i = 0; i < totalRevenue - 1; i++) {

for (j = i + 1; j < totalRevenue; j++) {

if (p[i].unitPrice * p[i].unitsSold > p[j].unitPrice
* p[j].unitsSold) {

int tempNumber = p[i].productNumber;
p[i].productNumber = p[j].productNumber;
p[j].productNumber = tempNumber;

string tempName = p[i].productName;
p[i].productName = p[j].productName;
p[j].productName = tempName;

double tempPrice = p[i].unitPrice;
p[i].unitPrice = p[j].unitPrice;
p[j].unitPrice = tempPrice;

int tempUnits = p[i].unitsSold;
p[i].unitsSold = p[j].unitsSold;
p[j].unitsSold = tempUnits;

}
}
}

cout << "The Top Selling Product is: " << endl;
cout << "Product Name: " << p[totalRevenue - 1].productName << endl;
cout << "total sales: " << p[totalRevenue - 1].unitsSold << endl;

cout << "\nThe Second Top Selling Product is: " << endl;
cout << "Product Name: " << p[totalRevenue - 2].productName << endl;
cout << "total sales: " << p[totalRevenue - 2].unitsSold << endl;

system("pause");
return 0;

}
You are making this a little bit harder than it needs to be.

First of all, your totalRevenue variable has absolutely nothing to do with revenue. I would change the name to totalItems. Then it will be meaningful. And there is no reason you need a separate i variable when you are reading in the data. Just use totalItems.

Now, on to the functionality.

You only need 1 loop.

Start with 2 Product objects, named top and second. Initialize them both to the value at p[0]. You might also want to add double revenue; to your struct so you can calculate and store the revenue for each item and you don't need to recalculate it all the time.

Loop through your p array. If the total revenue for the array element is greater than that in top, then move top into second and store the array value in top. Otherwise, if the array value is greater than the value in second, store the array value in second.

Topic archived. No new replies allowed.