首页 > 解决方案 > 从文件中读取数据,运算符 >>

问题描述

我有一类食谱:

...
#include <list> //I'm using list of the STL
....
class recipe{
 private:
   list<pair<string,unsigned int>> ing; //A list of the ingredients of one recipe. String for the name of the ingredient and unsigned int for the quantity of each ingredient
 public:
  ....

如何读取包含以下数据的文件以便进行编程operator >>

Salad;Tomatoe 50;Lettuce 100;Potatoe 60;Onion 10
Macaroni;Macaroni 250;Tomatoe 60;Oil 10
Fish and chips;fish 30;potatoe 30;Oil 40

我以为我可以这样做:

istream & operator >> (istream &i, recipe &r){
    string data, name;
    int quantity;

    stringstream s (line);  //read a line from the file
    getline(s,data," ");
    name = data;
    getline(s,data," ");
    quantity = atoi(data.c_str());
}

但显然每个食谱都有不同数量的成分,我不能那样做。那么,有什么帮助吗?

标签: c++

解决方案


把东西分成小块:

class recipe{
private:
    std::string name;
    std::list<std::pair<std::string,unsigned int>> ing;


    std::pair<std::string,unsigned int> parseIngredient(const std::string& s) {
        // do yourself
    }

    std::istream& readIngredients(istream& input) {
       ing.clear();
       std::string itemStr;
       while (std::getline(input, itemStr, ';')) {
           ing.push_back(parseIngredient(itemStr));
       }
       return input;
    }

public:
    std::istream& read(istream& input) {
        std::string line;
        if (std::getline(input, line)) {
            std::istringstream lineStream{ line };
            if (std::getline(lineStream, name, ';') && readIngredients(lineStream)) {
                return input;
            }
            input.setstate(std::ios::failbit);
        }
        return input;
    }
};

推荐阅读