Bool array and ofstream

I have been programming c++ for around half a year. And im trying to write to another file with a bool. I cant figure out how to just output what I have written to the txt file. Sorry for my english it isnt my mother tongue. Heres my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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;
		std::string txtname = "YourIngredients.txt";
		std::ofstream ingredientsList(txtname);
		ingredientsList << "Your ingredients are: " << std::endl;
		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;
					ingredientsList << ingredients[i] << std::endl;
				}
				break;
				ingredientsList.close();
			}
			
		if (i == maxIngredients){
			if (yourIngredients == "Exit" || yourIngredients == "exit")
			{
				exit = true;
			}
		}
	} 

}
Last edited on
Please use code tags: [code]Your code[/code]
Read this: http://www.cplusplus.com/articles/z13hAqkS/

In void add(){:
This if (yourIngredients[i] = true){ sets yourIngredients[i] to true the second time, which is entirely useless

This
1
2
break;
ingredientsList.close();
ends the loop after the first iteration, i.e. there's basically no loop.
Ive tried to make it in another loop but still didnt work.
So you want that the content of the file is discarded when you write the data in add()?

if so use trunc:
http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
No, I want to continue on what is allready writen in the txt file.
Then use std::ofstream::app in the constructor on line 40.
Topic archived. No new replies allowed.