0

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.2

A 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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • [`while(feof)` is always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). Just `while (ins >> product >> price) {` – KamilCuk Mar 24 '20 at 19:37
  • `Red Wine$20.3` will be surprisingly resistant to `ins >> product >> price` because of the whitespace. You will need `getline`. Use the dollar sign as the delimiter – user4581301 Mar 24 '20 at 19:40

1 Answers1

0

@cigien @user4581301 Thank you guys for your feedback really appreciate that but I kinda fixed it on my own since I was reading the product until the $-sign with getline(ins, product, '$'); before the while loop and the cursor was already at the price but with ins >> product >> price; after the while i was putting the price of the product on the product since i was reading the product two times. Just deleting product at ins >> product >> price making it ins >> price fixed it all.