Not sure what where to fix it

Hi guys

So I tried coding a program that works like a vending machine, when I compile it, it works. The problem is that, when I then run it, it gives me the right output but along with the error message that I set up:

//File: VendingMachine.cpp
#include <iostream>
using namespace std;
int main (void)
{
float option;

cout << "\n";
cout << "Insert coin" << "\n";
cout << "\n";
cout << "Press 1 for apple juice" << "\n";
cout << "Press 2 for twist lemon" << "\n";
cout << "Press 3 for water" << "\n";
cout << "Press 4 for sprite" << "\n";
cout << "Press 5 for fanta orange" << "\n";
cin >> option;

if (option == 1)
{
cout << "Apple juice" << "\n";
}
if (option == 2)
{
cout << "Twist lemon" << "\n";
}
if (option == 3)
{
cout << "Water" << "\n";
}
if (option == 4)
{
cout << "Sprite" << "\n";
}
if (option == 5)
{
cout << "Fanta orange" << "\n";
}
else
cout << "Error! Choice was not valid, here is your money back" << "\n";
return (0);

}

So can someone please tell me what I need to do so that it only outputs my option.

Kind regards
Matome
The else part belongs to the last if statement. You probably want to use else if to chain everything together:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (option == 1)
{
	cout << "Apple juice" << "\n";
}
else if (option == 2)
{
	cout << "Twist lemon" << "\n";
}
else if (option == 3)
{
	cout << "Water" << "\n";
}
else if (option == 4)
{
	cout << "Sprite" << "\n";
}
else if (option == 5)
{
	cout << "Fanta orange" << "\n";
}
else
	cout << "Error! Choice was not valid, here is your money back" << "\n";


else if is just an else part containing an if statement. If you want we could have written it as such:
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
if (option == 1)
{
	cout << "Apple juice" << "\n";
}
else 
{
	if (option == 2)
	{
		cout << "Twist lemon" << "\n";
	}
	else 
	{
		if (option == 3)
		{
			cout << "Water" << "\n";
		}
		else 
		{
			if (option == 4)
			{
				cout << "Sprite" << "\n";
			}
			else 
			{
				
				if (option == 5)
				{
					cout << "Fanta orange" << "\n";
				}
				else
				{
					cout << "Error! Choice was not valid, here is your money back" << "\n";
				}
			}
		}
	}
}

But writing it the first way is often preferred.
Thank you very much :-D
Last edited on
Could also make use of a switch statement here or a const char* array of size 5. Depending on what the user chooses - will determine the index in the array.
I wish I knew what that is. Thing is that I am only learning programming this year, I have no background or anything, so I am only using what our lecturer has taught us so far, and the format I am using includes all the tools I have been taught thus far.
Topic archived. No new replies allowed.