【发布时间】:2015-11-30 23:05:42
【问题描述】:
我正在尝试按项目的成分创建一个可搜索的食谱数据库。我正在尝试创建遍历字符串向量(其中保存了每种成分)的 for 循环并搜索文件并比较它们。现在,我只想让它输出“你好!”如果有比赛。经过我所有的摆弄,要么有 100 个 Hello!s(绝对不正确),要么没有。代码如下:
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的一次迭代之后,您处于文件的末尾,并且所有后续迭代将立即中断,因为没有任何内容可供阅读。尝试反转你的循环。 -
啊,是的。钟华是对的。那会是个问题。
-
查看上面的内容,您可能需要使用类似于 string::find, cplusplus.com/reference/string/string/find 的内容,除非用户输入“1 汤匙玉米淀粉”。此外,请确保您正在处理在 C++ 中索引从零开始的事实。因此,三个成分只需要:0、1 和 2 即可访问数组中的所有成分。但是你会通过 i 达到 3
-
多年来我一直在研究食谱数据库系统。我强烈建议使用真实的外部数据库。乱用数据文件是对生产力的浪费。