【发布时间】:2015-03-30 09:30:26
【问题描述】:
我已经编写 c++ 大约半年了。我试图用布尔值写入另一个文件。我不知道如何将我写入的内容输出到 txt 文件中。对不起我的英语不是我的母语。这是我的代码:
int main(){
system("cls");
std::cout << "1. Add ingredient" << std::endl;
std::cout << "2. Delete ingredient" << std::endl;
std::cout << "3. Show you ingrediens" << std::endl;
std::cout << "4. Show recipies" << std::endl;
std::cout << "5. Exit" << std::endl;
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
add();
break;
case 2:
deleteIngredient();
break;
case 3:
showIngredient();
break;
case 4:
showRecipies();
}
}
void add(){
system("cls");
const int maxIngredients = 10; // max ingredients
std::string ingredients[maxIngredients]{ /*kjøtt*/ "beef", "chicken", "pork", "lamb", "rabbit",
/*fisk*/ "salmon", "tuna"}; // ingredients
bool hasingredient[maxIngredients] {}; //bool for ingredients
bool exit = false; // exit request
std::cout << "Welcome, type your ingredients " << std::endl;
while (!exit){
std::string yourIngredients;
std::cin >> yourIngredients;
int i;
for (i = 0; i < maxIngredients; i++)
if (yourIngredients == ingredients[i]){
yourIngredients[i] = true; // <================ set flag of indegrient
if (yourIngredients[i] = true){
std::cout << "You have choosen " << ingredients[i] << std::endl;
}
break;
}
std::string txtname = "YourIngredients.txt";
std::ofstream ingredientsList(txtname);
ingredientsList << "Your ingredients are: " << std::endl;
int y = 0;
for (y = 0; y < maxIngredients; y++){
if (hasingredient[y] = true){
ingredientsList << ingredients[y] << std::endl;
}
}
ingredientsList.close();
if (i == maxIngredients){
if (yourIngredients == "Exit" || yourIngredients == "exit")
{
exit = true;
}
}
}
}
【问题讨论】: