如何在 c++ 中加载 2 个文件?

How to load 2 files in c++?

本文关键字:文件 加载 c++      更新时间:2023-10-16

这是蛋糕.txt:

tiramisu;2;7;1;6;3;9;
strawberry with white chocolade;2;8;4;11;9;10;
creamcake;2;5;10;9;
chocoladecake;2;12;9;3;5;13;10;

这是组件.txt:

1;pepper
2;flour
3;sugar
4;chocolade
5;salt
6;eggs
7;caffe
8;butter
9;cheese
10;cream
11;strawberry
12;desiccated coconut
13;water

我想像这样显示此文件:

Cheesecake:
-butter
-cream
-cheese

现在程序向我显示这样的代码:芝士蛋糕;2;3;7;5; 这是我的代码

int Cake(const char* nazwaPliku)
{
ifstream we;
we.open(nazwaPliku);
if( !we.good() )
{
cerr << "Problem with file read"<<endl;
return -1;
}
string cak;
while(getline(we,cak))
{
cout<<"Name cake: "<<cak<<'n';
}
we.close();
}

int main()
{
int name = Cake("cakes.txt");
int names = Cake("component.txt");

return 0;
}

我不知道如何解决第二部分。我希望有人展示并解释我。

因此,看起来您正在尝试构建一个给定成分列表和所需成分编号的食谱。

您可以通过按提供顺序保留所有可能成分的vector来解决此问题,然后访问载体中的某些成分。

这是我的程序,它这样做:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(){
ifstream fin("component.txt");
// store all the different ingredients
vector <string> components;
string temp;
while(fin >> temp){
components.push_back(temp.substr(2)); // ignore the first two characters
}
fin.close();
fin.open("cake.txt");
while(fin >> temp){ // input the next line
string str;
vector <int> semicolons;
// find all semicolons; they separate the ingredients
for(unsigned int i = 0; i < temp.size(); ++i){
if(temp[i] == ';'){semicolons.push_back(i);}
}
// "Cheesecake;"
str.push_back(temp.substr(0, semicolons[0]+1);
for(unsigned int i = 1; i < temp.size(); ++i){
string num = temp.substr(semicolons[i-1], semicolons[i]-semicolons[i-1]);
str.push_back(components[stoi(num) - 1]);
} // "Cheesecake;milk;water;egg;"
// "Cheesecake;milk;water;egg"
str.pop_back();
}
return 0;
}