벡터에 대해 자세히 배우고 그 안에 개체를 저장하려고합니다. 나는 txt 파일에서 데이터를 읽는다. 내가하고있는 실수가 작동하지 않는다는 것을 나는 볼 수 없다. 내 MAIN.CPP 파일에서Object Vector C++
Food::Food(string newName, int newCalories, int newCost) {
this->name = newName;
this->calories = newCalories;
this->cost = newCost;
}
난 그냥 객체 리더 (지금은없는 생성자)를 만드는거야 및 :
여기 내 주요 방법은
void Reader::readFoodFile() {
string name;
int cal, cost;
ifstream file;
file.open("food.txt");
while (file >> name >> cal >> cost) {
Food f(name, cal, cost);
foodStorage.push_back(f);
}
}
void Reader::getStorage() {
for (unsigned int i = 0; i < foodStorage.size(); i++) {
cout << foodStorage[i].getName();
}
}
그리고 여기 내 식품 생성자되어 있습니다 메소드를 호출하십시오.
int main(int argc, char** argv) {
Reader reader;
reader.readFoodFile();
reader.getStorage();
}
벡터를 txt 파일의 데이터를 가져 와서 (지금은) 인쇄하는 개체로 채우고 싶습니다.
제안 사항?
편집; 내 .txt 파일 레이아웃은 다음
apple 4 2
strawberry 2 3
carrot 2 2
내 Food.h 및 Reader.h
#ifndef FOOD_H
#define FOOD_H
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
class Food {
public:
Food();
Food(string, int, int);
Food(const Food& orig);
virtual ~Food();
string getName();
int getCalories();
int getCost();
void setCost(int);
void setCalories(int);
void setName(string);
int calories, cost;
string name;
private:
};
#endif /* FOOD_H */`
and Reader.h
`#ifndef READER_H
#define READER_H
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include "Food.h"
using namespace std;
class Reader {
public:
Reader();
Reader(const Reader& orig);
virtual ~Reader();
void readFoodFile();
void getStorage();
vector<Food> foodStorage;
private:
};
#endif /* READER_H */
표시되는 잘못된 동작은 무엇입니까? – yiding
getStorage()를 호출 할 때 출력이 없으며 빈 줄만 표시됩니다. – ChrisA
코드를 디버깅 할 때 무엇을 사용하고 있습니까? – johnathon