所以我的输入文件就是这个
Target
Inventory:
tech 200 5
food 10 100
clothes 15 10
我需要能够记录商店名称及其库存
到目前为止,我有这个工作代码
struct item {
std::string kind;
int price;
int quanity;
};
int main(int argc, char **argv){
std::fstream file;
file.open(argv[1]);
if (file.fail()){
std::cerr << "Error opening file!\n";
exit(1);
}
std::vector<struct item> inventory;
std::string name;
struct item target;
while(!file.eof()){
file >> name;
if(name == "Inventory:"){
while(file >> target.kind >> target.price >> target.quanity){
inventory.push_back(target);
}
break;
}
}
for(auto a : inventory){
std::cout << "Kind: " << a.kind << "\tPrice: " << a.price << "\tQuanity: " << a.quanity << std::endl;
}
所以这段代码工作正常,但显然文本文件应该是这样的
Target
Inventory:
tech,200,5
food,10,100
clothes,15,10
现在我似乎无法弄清楚当每个项目用逗号分隔时如何工作。请帮忙!我已经尝试在第二个while循环中添加这一行,但它不好
if (file.peek() == ','){
file.ignore();
}