所以我试图通过从输入文件中获取信息来在C ++中创建一个对象数组(Item对象)。第一行包含物品的数量以及存储它们的行李的总容量。之后的每一行都包含一个项目的名称,利润和中间有空格的权重。
输入文件示例:
7 25
orange 50 5
banana 60 10
kitchensink 140 20
strawberry 100 14
tangerine 10 5
puppy 25 12
grape 30 7
如何设置我的程序/构造函数,使其不只读取第一行并逐行读取项目?
#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;
}
}