c++ - 从文件中读取数据,运算符 >>
问题描述
我有一类食谱:
...
#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());
}
但显然每个食谱都有不同数量的成分,我不能那样做。那么,有什么帮助吗?
解决方案
把东西分成小块:
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;
}
};
推荐阅读
- angular - 在升级面临构建问题的最新 angular slickgrid 版本时
- javascript - 在目录中使用 mix minify
- python - 如何从 Python 中的变量模块调用函数?
- node.js - fsPromises.open() 在追加模式下打开时抛出错误
- java - 使用java在谷歌表格中执行QUERY公式
- node.js - 使用 github typescript 作为依赖项 - SyntaxError: Cannot use import statement outside a module
- cassandra - 电子商务和连接的 cassandra 数据建模
- react-native - createStackNavigator Stack.Screen 未呈现任何组件,但已指定
- beta - Ballerina - Swan Lake Beta 1 - 如何在模块中调用函数?
- quasar-framework - 如何更改 QEditor 插槽的宽度?