So I am trying to create an array of objects (the Item object) in C++ by getting the information from an input file. The first line contains the number of items there are and the total capacity of a bag to store them. Every line after that contains the name of an item, the profit, and the weight with spaces in between.
Example of an input file:
7 25
orange 50 5
banana 60 10
kitchensink 140 20
strawberry 100 14
tangerine 10 5
puppy 25 12
grape 30 7
How do I set up my program/constructor so it's not reading only the first line and will read the items in line by line?
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;
static ifstream fr;
//class for item object
class Item
{
public:
//constructor that will get/initialize the name, weight,
//profit of item from input file and initialize/calculate the ratio
Item()
{
fr>>name>>p>>w;
r=p/w;
}
string getName()
{return name;}
int getWeight()
{return w;}
int getProfit()
{return p;}
double getRatio()
{return r;}
private:
string name;
int w, p;
double r;
};
int main()
{
int n, c;
//ifstream fr;
fr.open("inputp1.txt");
fr>>n>>c; //get n from input file //get capacity
//create an array of Items objects reading in from the input file based on n
Item tosteal[n];
for (int i=0; i<n; i++)
{
tosteal[i]= Item();
}
fr.close();
for (int i=0; i<n; i++)
{
cout <<"Profit: "<<tosteal[i].getProfit()<<endl;
cout <<"Weight: "<<tosteal[i].getWeight()<<endl;
cout <<"Name: "<<tosteal[i].getName()<<endl;
cout <<"Ratio: "<<tosteal[i].getRatio()<<endl;
}
}