0

ベクトルについてもっと学び、そこにオブジェクトを格納しようとしています。txt ファイルからデータを読み取っています。それが機能しないという間違いを犯していることはわかりません。

ここに私の主な方法があります

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();
    }
}

そして、ここに私の Food コンストラクターがあります:

Food::Food(string newName, int newCalories, int newCost) {
    this->name = newName;
    this->calories = newCalories;
    this->cost = newCost;
}

私の main.cpp ファイルでは、オブジェクト Reader (現在はコンストラクターなし) を作成し、メソッドを呼び出しています。

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 */
4

2 に答える 2

0

あなたのexeは、あなたが期待するものとは異なる相対パスで実行されていると思います。file.open() を呼び出した後、file.good() が true であることを確認します。この問題は、プログラミング IDE (Visual Studio など) が、exe が書き込まれている場所とは異なる作業フォルダーで exe を実行する場合によく発生します。

于 2013-05-02T02:02:53.950 に答える