Basic Variables and Functions Question

I am new to programming in C++ and created this program, this was mostly to test functions, but has led me to some trouble.
When I run this program, the money variable resets to 20 after the code executes the buyItem function. Is there any way around this, and are there any other tips you could give me?
Thanks in advance.

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
#include <iostream>
#include <string>
using namespace std;

void buyItem( double money , double cost , string name )
{
		if((money-cost) > -1)
		{
			money = (money-cost);
			cout <<" You got a " << name << "!\n";
			cout <<"You have " << money << " dollars left!\n";
			cin.ignore();
		}
		else
		{
			cin.ignore();
		}
}
int main()
{
	int imput;
	double money;
	string name;
	money = 20;
	cout <<" Hello! welcome to my store, you have " << money << " dollars left!\n";
	while( money > 0 )
	{
	cout <<"What do you want to buy?\n";
	cout <<"1.) Soda ($2.00)\n";
	cout <<"2.) Magazine ($7.00)\n";
	cout <<"3.) Chocolate bar ($1.00)\n";
	cout <<"4.) Donut ($1.50)\n";
	cin>> imput;
	switch (imput)
	{
		case 1:
			buyItem(money,2,"soda");
		break;

		case 2:
			buyItem(money,7,"magazine");
		break;

		case 3:
			buyItem(money,1,"chocolate bar");
		break;
		
		case 4:
			buyItem(money,1.50,"donut");
		break;
	}
	}
	cout << "Looks like you're out of money!\n";
	cin.ignore();
}
Seems like you should be passing the double money parameter in buyItem by reference instead of by value as you currently have:

void buyItem( double money , double cost , string name )

should be:

void buyItem( double & money , double cost , string name )
Thank you so much! It solved my problem.
Topic archived. No new replies allowed.