I am trying to solve this assignment:
Write a program to read a file called prices.txt, which contains an arbitrary number of lines of names of products and prices, separated by a dollar ($). After reading the products, your program must analyze all of them and print statistics about the prices – how many products’ prices are in the ranges - (0, 10], (10, 20] and above 20. The text file can contain:
Coca-cola$1.45
Red Wine$20.3
Whiskey$100
Water$1.2A sample output of the program, for the above input, as shown below:
0-10: 2 product(s)
10-20: 0 product(s)
above 20: 2 product(s)
This code is as far as I have gotten into it:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream ins; // declare an input file stream object
ins.open("prices.txt"); // open the file
if (ins.fail()) { // check if there was an error
cout << "Error opening file";
return -1;
}
int count1 = 0; //variable to count how many prices are from 0 - 10
int count2 = 0; //variable to count how many prices are from 10 - 20
int count3 = 0; //variable to count how many prices are above 20
string product;
float price = 0;
getline(ins, product, '$');
while (!ins.eof()) {
ins >> product >> price;
if (price > 0 && price <= 10.0) {
count1++;
}
else if (price > 10.0 && price <= 20.0) {
count2++;
}
else {
count3++;
}
ins.ignore(100, '\n'); // ignore the next newline
getline(ins, product, '$'); // read the product name until the $ sign
}
ins.close(); // close the file
cout << "0-10: " << count1 << " product(s) " << endl;
cout << "10-20: " << count2 << " product(s) " << endl;
cout << "above 20: " << count3 << " product(s) " << endl;
return 0;
}