Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- #include <algorithm>
- using namespace std;
- struct Recipe {
- string name;
- vector<string> ingredients;
- string directions;
- };
- // Function to read a recipe from a file
- Recipe read_recipe(string filename) {
- ifstream file(filename);
- Recipe recipe;
- if (file.is_open()) {
- getline(file, recipe.name);
- string ingredient;
- while (getline(file, ingredient)) {
- recipe.ingredients.push_back(ingredient);
- }
- getline(file, recipe.directions, '\0');
- file.close();
- } else {
- cerr << "Error: could not open file '" << filename << "'\n";
- }
- return recipe;
- }
- // Function to write a recipe to a file
- void write_recipe(string filename, Recipe recipe) {
- ofstream file(filename);
- if (file.is_open()) {
- file << recipe.name << '\n';
- for (string ingredient : recipe.ingredients) {
- file << ingredient << '\n';
- }
- file << recipe.directions;
- file.close();
- } else {
- cerr << "Error: could not open file '" << filename << "'\n";
- }
- }
- // Function to search for recipes containing a list of ingredients
- vector<string> search_recipes(vector<string> ingredients, vector<string> filenames) {
- vector<string> results;
- for (string filename : filenames) {
- Recipe recipe = read_recipe(filename);
- bool found = true;
- for (string ingredient : ingredients) {
- if (find(recipe.ingredients.begin(), recipe.ingredients.end(), ingredient) == recipe.ingredients.end()) {
- found = false;
- break;
- }
- }
- if (found) {
- results.push_back(recipe.name);
- }
- }
- return results;
- }
- int main() {
- // Read recipe files
- vector<string> filenames = {"recipe1.txt", "recipe2.txt", "recipe3.txt"};
- vector<Recipe> recipes;
- for (string filename : filenames) {
- recipes.push_back(read_recipe(filename));
- }
- // Write new recipe
- Recipe new_recipe;
- new_recipe.name = "Pizza";
- new_recipe.ingredients = {"Dough", "Tomato sauce", "Mozzarella cheese", "Pepperoni"};
- new_recipe.directions = "1. Preheat oven to 425 degrees F.\n2. Roll dough into a circle.\n3. Spread tomato sauce on dough.\n4. Sprinkle cheese and toppings on pizza.\n5. Bake for 10-15 minutes.\n";
- write_recipe("recipe4.txt", new_recipe);
- // Search for recipes containing certain ingredients
- vector<string> ingredients = {"Cheese", "Pepperoni"};
- vector<string> results = search_recipes(ingredients, filenames);
- if (results.empty()) {
- cout << "No recipes found containing " << ingredients[0] << " and " << ingredients[1] << endl;
- } else {
- cout << "Recipes containing " << ingredients[0] << " and " << ingredients[1] << ":\n";
- for (string result : results) {
- cout << "- " << result << endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement