#include <iostream>
#include <fstream> //added fstream header
usingnamespace std;
int main()
{
int cars[10];
int sum = 0;
int max;
int salesPerson;
fstream inFile; //declared input file
inFile.open("cars.txt");
for (int j = 0; j < 10; j++)
{
inFile >> cars[j];
}
cout << "The total number of cars sold = " << sum << endl;
max = cars[0];
salesPerson = 1;
for (int j = 1; j < 10; j++)
if (max > cars[j])
{
max = cars[j];
salesPerson = j;
}
cout << "The salesperson selling the maximum number of cars is salesperson "
<< salesPerson << endl;
cout << "Salesperson " << salesPerson << " sold "
<< max << " cars last month." << endl;
cout << endl;
inFile.close();
return 0;
}
The program is supposed to take the number of car sales from 10 salesmen from an input file and return the total cars sold, who sold the most, and how many they sold. See below.
cars.txt:
5 6 11 8 3 4 1 7 2 5
Sample Run:
The total number of cars sold = 52
The salesperson selling the maximum number of cars is salesperson 3
Salesperson 3 sold 11 cars last month.
Given I am a beginner and there are several problems with this script, I suppose I should take it one problem at a time. My first problem is how do you input the 10 integer values from the file individually? I appreciate any and all input.
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
fstream inFile("cars.txt");
if (!inFile.is_open()) {
cout << "Cannot open the file\n";
return 1;
}
int sum = 0;
int max = 0;
int salesPerson = 0;
for (int s = 1, n = 0; inFile >> n; ++s) {
sum += n;
if (n > max) {
max = n;
salesPerson = s;
}
}
cout << "The total number of cars sold = " << sum << endl;
cout << "The salesperson selling the maximum number of cars is salesperson "
<< salesPerson << endl;
cout << "Salesperson " << salesPerson << " sold "
<< max << " cars last month." << endl;
inFile.close();
}
The total number of cars sold = 52
The salesperson selling the maximum number of cars is salesperson 3
Salesperson 3 sold 11 cars last month.