Я пытаюсь создать базу данных рецептов для поиска по ингредиенту для проекта. Я новичок в C++, так голый со мной. Сейчас я пытаюсь создать цикл for, который проходит через вектор строки (который содержит каждый ингредиент, сохраненный в нем), и поиск по файлу и сравнение их. Прямо сейчас, я просто хочу, чтобы он выводил «Привет!». если они совпадают. При всей моей игре, либо 100 Hello! S (определенно не так), либо нет. Вот код. Заранее благодарю.Поиск в текстовых файлах для определенного слова C++
int main()
{
int y;
cout << "Hello! Welcome to Abby's Recipe Calculator." << endl << endl;
cout << "Please select an option: 1 to search by ingredient or 2 to browse recipes..." << endl;
cin >> y;
vector <string> ingreds;
ingreds.reserve(4);
if (y == 1)
{
ingredientvector(ingreds); // calls function to fill vector w/ ingredients
}
//else if (y == 2)
//{
//call recipe function...
//}
Search x1(ingreds); //assigns ingredients to object vector
recipesearch(x1.getingreds());
system("pause");
return 0;
}
void ingredientvector(vector<string>& x)
{
cout << "SEARCH BY INGREDIENT" << endl;
cout << "Please enter up to three ingredients... " << endl;
for (int i = 0; i < 4; i++)
{
x.push_back(" ");
getline(cin, x[i]);
if (x[i] == "1")
{
break;
}
}
}
void recipesearch(const vector<string>& ingredientlist) //ifstream& recipes)
{
ifstream myrecipes;
string line;
string ingredient;
myrecipes.open("recipes.txt");
if (myrecipes.is_open())
{
for (int i = 0; i < 4; i++)
{
ingredient = ingredientlist[i];
while(getline(myrecipes, line)){
if (ingredient == line)
{
cout << "Hello!" << endl;
}
else
{
break;
}
}
}
}
else cout << "Unable to open recipe file!";
myrecipes.close();
}
Вот пример рецепта используется:
Cheese-y Ramen
Prep Time: 5 minutes
Cook Time: 20 minutes
Total Time: 25 minutes
Servings: 2
Ingredients:
8 oz cheddar cheese
1 tablespoon cornstarch
¾ cup milk
2 packages ramen noodles
Directions:
1. Grate cheddar cheese and add with cornstarch into a small bowl
2. Combine with milk in a medium saucepan and cook on medium to low heat until consistent. Keep warm until serving.
3. In a separate pan boil ramen noodles. Set aside the included flavor packets.
4. Once boiling, drain the noodles and combine with cheese.
Recipe from Buzzfeed
Можете ли вы добавить пример своего файла рецепта. –
После одной итерации 'i' вы находитесь в конце своего файла, и все последующие итерации сразу же будут нарушены, так как читать нечего. Попробуйте изменить ваши петли. – usr2564301
А, да. Jongware верна. Это будет проблемой. –