【问题标题】:C++ bool with ofstream带有 ofstream 的 C++ 布尔值
【发布时间】: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;
        }
    }
} 

}

【问题讨论】:

    标签: c++ boolean ofstream


    【解决方案1】:

    如果我正确理解你的英语,你想打印你写的文件,不是吗?

    添加这个:

    std::cout << ingredients[y] << std::endl;
    

    之后:

    ingredientsList << ingredients[y] << std::endl;
    

    我注意到你有 if 情况:

    if (hasingredient[y] = true){
    

    这不是比较,而是分配。

    【讨论】:

    • 如您所见,您可以写 10 种不同的成分,例如,当您写 1 时,然后是牛肉,然后退出。我想将它添加到 YourIngrediens.txt 文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2013-10-08
    • 2020-03-16
    • 2021-02-26
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多