Help Needed asap! I really need help!!!!!!

I created the code below with three functions, I am having trouble implementing the following:

*Ask customers to select multiple products and quantities
*Print the order summary, including the products, the quantities, and the
total price for each product
*Calculate and print the total price for the order

I could really use some help adding these into my code because I am lost.

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Use of functions
#include <iostream>
#include <string>
using namespace std;


void displayMenu(string userName)
{

	cout << userName << ", Please select the beverage you would like to purchase from the menu: " << endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1" << endl;
	cout << "2 - Soda $2" << endl;
	cout << "3 - Iced Tea $3" << endl;
	cout << "X - Exit " << endl << endl;
}

// View menu Option 1 for <name>
void viewOption1(string name)
{
	cout << "Name: " << name << endl;
	cout << "Selection: " << "Water," << " Price: $1" << endl;
}


// View menu Option 2 for <name>
void viewOption2(string name)
{
	cout << "Name: " << name << endl;
	cout << "Selection: " << "Soda," << " Price: $2" << endl;
}


// View menu Option 3 for <name>
void viewOption3(string name)
{
	cout << "Name: " << name << endl;
	cout << "Selection: " << "Iced Tea," << " Price: $3" << endl;
}


int main(void)
{
	char selection = ' ';
	string name = "";

	//Ask user for her/his name
	cout << "Please enter your name ==> ";
	getline(cin, name);

	//display user name
	cout << "Hello " + name << endl;

	do
	{
		// display menu
		displayMenu(name);
		// read user selection
		cin >> selection;

		switch (selection)
		{
		case '1':
			cout << "You selected Water" << endl;
			viewOption1(name);
			break;
		case '2':
			cout << "You selected Soda" << endl;
			viewOption2(name);
			break;
		case '3':
			cout << "You selected Iced Tea" << endl;
			viewOption3(name);
			break;
		case 'X':
		case 'x':
			cout << "Thank you!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x');

	return 0;
}
Last edited on
Your problem is similar to this thread.
http://www.cplusplus.com/forum/beginner/218985/#msg1009375

I looked at that post and it seems so different and not informative to my situation. I really need help with these 3 implementations. to my code above.

*Ask customers to select multiple products and quantities
*Print the order summary, including the products, the quantities, and the
total price for each product
*Calculate and print the total price for the order
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Use of functions
#include <iostream>
#include <string>
using namespace std;


void displayMenu(string userName)
{

	cout << userName << ", Please select the beverage you would like to purchase from the menu: " << endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1" << endl;
	cout << "2 - Soda $2" << endl;
	cout << "3 - Iced Tea $3" << endl;
	cout << "X - Exit " << endl << endl;
}

// View option 1 for <name>
void viewOption1(string name)
{
	cout << "Name: " << name << endl;
	cout << "Selection: " << "Water," << " Price: $1.45" << endl;
}


// View option 2 for <name>
void viewOption2(string name)
{
	cout << "Name: " << name << endl;
	cout << "Selection: " << "Soda," << " Price: $2.98" << endl;
}


// View option 3 for <name>
void viewOption3(string name)
{
	cout << "Name: " << name << endl;
	cout << "Selection: " << "Iced Tea," << " Price: $3.29" << endl;
}


int main(void)
{
	char selection = ' ';
	string name = "";
	double price, subtl;
	int code, quantity;
	double total = 0; //allows you to use += to calculate produce subtotal since no tax. 
					  //Will also reset total to 0 when you want to serve a new customer.

					  //Ask user for her/his name
	cout << "Please enter your name ==> ";
	getline(cin, name);

	//display user name
	cout << "Hello " + name << endl;

	cout << "Would you like to see our drink menu: (Y/N)\n";
	cin >> selection;

	while (selection == 'y' || selection == 'Y')
	{
		displayMenu(name);

		do
		{
			// display menu
			//displayMenu(name);
			cout << "Please select: ";
			// read user selection
			cin >> selection;


			switch (selection)
			{
			case '1':
				cout << "You selected Water" << endl;
				cout << "Enter Quantity:";
				cin >> quantity;
				if (quantity <= 0)
				{
					cout << "Invalid Quantity" << endl;
					cin >> quantity;
				}
				price = 1.45;
				subtl = (quantity*price);
				cout << "Subtotal $\n" << subtl << endl;
				viewOption1(name);
				break;
			case '2':
				cout << "You selected Soda" << endl;
				cout << "Enter Quantity:";
				cin >> quantity;
				if (quantity <= 0)
				{
					cout << "Invalid Quantity" << endl;
					cin >> quantity;
				}
				price = 2.98;
				subtl = (quantity*price);
				cout << "Subtotal $\n" << subtl << endl;
				viewOption2(name);
				break;
			case '3':
				cout << "You selected Iced Tea" << endl;
				cout << "Enter Quantity:";
				cin >> quantity;
				if (quantity <= 0)
				{
					cout << "Invalid Quantity" << endl;
					cin >> quantity;
				}
				price = 3.29;
				subtl = (quantity*price);
				cout << "Subtotal $\n" << subtl << endl;
				viewOption3(name);
				break;
				cout << "Thank you!!!" << endl;
				break;
			case '0'://Sentinal value that gives subtotal (because no tax) then ends your function.
				cout << "Subtotal: \n" << total << endl;
				break;
				// other than 1, 2, 3 and X...
			default: cout << "Invalid selection. Please try again ";
				// no break in the default case
			}
			total += subtl; //will add all the produce values up. is read as total=total+subt
		} while (selection != 0);//checks if code = 0 at the end of function wont end till it is.
	}
	cout << "Would you like to continue shopping?(Y/N)";
	cin >> selection;
}


This is what I came up with so far please advise on the following featured needed:

*Ask customers to select multiple products and quantities (I believe my code now has this)
*Print the order summary, including the products, the quantities, and the total price for each
product
*Calculate and print the total price for the order

Help ASAP!
Last edited on
Hi, I appreciate the fact that you are putting effort to solve your problem.

Before i give you a working code, let me walk you through a story.

In the world, there are about 3 billion people, an English man will refer to one of these 3 billion as a Person. Each person like you and i have
- name
- age
- height etc
- weight
At each time, you know how to describe yourself e.g My name is Somebody, I am 2 years old and 98 cm tall. From height and weight, one can derive the Body Mass Index (BMI).

The same applies to this your program.

You have beverages each has a name, a price (per unit), quantity ordered and from the price and quantity ordered, one can derive the total cost for the beverage.

Now in programming terms, we can contain a Beverage in what is called Class or Struct difference=> https://stackoverflow.com/a/92951

If you don't know what these mean then your lecturer wanted you to research it, atleast a Struct http://www.cplusplus.com/doc/tutorial/structures/

I directed you to that thread because this solution http://www.cplusplus.com/forum/beginner/218985/#msg1009561 uses a struct and it was appropriate for the problem.

Read http://www.cplusplus.com/doc/tutorial/structures/ to get a better understanding. Without which, you might find it difficult understanding what i have done.

This is how you should target your problem
1. Make a Struct (i call it Beverage) that holds each beverage's name, price, quantity and any other function that you would like to have eg. info() to display what you write in viewOptionX()

2. To get a total, you have to hold these beverages in some sort of container. Use std::vector http://www.cplusplus.com/reference/vector/vector/ if you have reached there otherwise use c array http://www.cplusplus.com/doc/tutorial/arrays/

3. Make a function to get quantity

4. Make a function to display summary of all orders

5. Make a function to calculate total cost of all orders

This is how i did it

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Use of functions
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

/**
 * @struct	Beverage
 *
 * @brief	Let each beverage have a name, price and quantity
 * 			and even information about itself
 */

struct Beverage
{
	string name;	/**< The name */
	int quantity{}; /**< The quantity */
	double price{}; /**< The price */

	void info() 
        {
		cout << setw(10) << left << "Name" << name << "\n"
			<< setw(10) << left << "Price" << "$" << price << "\n"
			<< setw(10) << left << "Quantity" << quantity << "\n"
			<< setw(10) << left << "Total" << "$"
			<< quantity * price << "\n" << endl;
	}
	void simpleInfo() 
        {
		cout << "Selection: " << name << ", price per unit: $" << price << endl;
	}

	 Beverage() {}
        ~Beverage(){}
	Beverage(string n, double p) {
		name = n;
		price = p;
	}
}; // END OF STRUCT

double totalCost(Beverage beverages[], int numOfBeverages);
void orderSummary(Beverage beverages[], int numOfBeverages);
int getQuantity();
void doShopping();


void displayMenu(string userName)
{

	cout << endl << endl
		<< userName
		<< ", Please select the beverage you would like to purchase from the menu: "
		<< endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1" << endl;
	cout << "2 - Soda $2" << endl;
	cout << "3 - Iced Tea $3" << endl;
	cout << "X - Exit " << endl << endl;
}

int main(void)
{
	doShopping();

	return 0;
}

/**
 * @fn	int getQuantity()
 *
 * @brief	Gets the quantity
 * 			NB: There is no attempt to check for correct input
 * 			if you want to check that the number is really valid,
 * 			check this
 * 			http://www.cplusplus.com/forum/beginner/230666/#msg1043359
 * 			or other solutions in the same thread or google 
 *
 *
 * @return	The quantity.
 */

int getQuantity() {
	int quantity = 0;
	cout << "Enter quantity : ";
	cin >> quantity;
	return quantity;
}

/**
 * @fn	double totalCost(Beverage beverages[], int numOfBeverages)
 *
 * @brief	Total cost
 *
 * @param	beverages	  	The beverages.
 * @param	numOfBeverages	Number of beverages.
 *
 * @return	The total cost.
 */

double totalCost(Beverage beverages[], int numOfBeverages) {
	double totalCost = 0;

	for (int i = 0; i < numOfBeverages; i++) {
		totalCost += (beverages[i].price*beverages[i].quantity);
	}
	return totalCost;

}

/**
 * @fn	void orderSummary(Beverage beverages[], int numOfBeverages)
 *
 * @brief	Order summary for items selected
 *
 * @param	beverages	  	The beverages.
 * @param	numOfBeverages	Number of beverages.
 */

void orderSummary(Beverage beverages[], int numOfBeverages)
{
	cout << "\n======= ORDER SUMMARY ====" << endl;
	cout << "Items selected" << endl << endl;
	for (int i = 0; i < numOfBeverages; i++) {
		// only show beverages that has at least one order
		if (beverages[i].quantity > 0) {
			beverages[i].info();
		}
	}
}

void doShopping()
{
	// declare our beverages 
	Beverage water("Water", 1),
		soda("Soda", 2),
		iceTea("Ice Tea", 3);

	// make an array to hold the beverages
	// I strongly recommend using std::vector for this
	Beverage beverages[] = { water, soda, iceTea };

	char selection = ' ';
	string name = "";

	//Ask user for her/his name
	cout << "Please enter your name ==> ";
	getline(cin, name);

	//display user name
	cout << "Hello " + name << endl;

	do
	{
		system("cls");
		// display menu
		displayMenu(name);

		// read user selection
		cout << "Your selection: ";
		cin >> selection;

		switch (selection)
		{
		case '1':
			beverages[0].simpleInfo();
			beverages[0].quantity += getQuantity();
			break;
		case '2':
			beverages[1].simpleInfo();
			beverages[1].quantity += getQuantity();
			break;
		case '3':
			beverages[2].simpleInfo();
			beverages[2].quantity += getQuantity();
			break;
		case 'X':
		case 'x':
			orderSummary(beverages, 3);
			if (totalCost(beverages, 3) > 0) {
				cout << "\nGrand total = $" << totalCost(beverages, 3) << endl;
			}
			cout << "\nThank you!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x');
}


Three things to note:
1. Always use code tags http://www.cplusplus.com/articles/jEywvCM9/
2. As a beginner, paste your questions in the beginner forum. Your are more likely to get help there.
3. This forum is not an SOS forum so wanting help ASAP is not the best way of asking for help. People come here to help at their spare time.
Last edited on
Hi blongho,

Thank you so much for your help. I am still encountering a few problems after entering the selection and quantity if I hit X my program ends. The summary is never displayed? I am also encountering an error where if I hit X or x my program instantly closes my Thank you message is not read.

I need some pointers on doing the following:

*Print the order summary, including the products, the quantities, and the total price for each product
*Calculate and print the total price for the order

Currently no order summary is shown nor does it calculate the grand total. After I added to me code I plugged your code into visual studios and same thing does not display I see it shows but the program ends so quickly I need help figuring out how to solve this and X or x ends the program instantly.

Please advise. Thank you,
Joseph
Last edited on
Hi Joseph,
First and foremost, if your program closes so quickly, in VS, you, can fix it like this

https://stackoverflow.com/a/15595559

Can you paste your most recent code here so i see? Yes, your current code will not
work as you imagine.

This is why:
1. When you give subtl a new value
subtl = (quantity*price); Here subtl takes whatever quantity and price. Next time, you do it, it takes the next value and discards the previous one.
1
2
subtl = (quantity*price); // should be
subtl += (quantity*price);


Besides, each item ought to have its own subtl and quantity since you need it to occur multiple times.
eg. double waterSubtl, sodaSubtl etc

The aim of using functions is to be able to re-use the function in many places and avoid repetition.
You could condence viewOption1(string name), viewOption2(string name) viewOption3(string name)
to

void viewOption(string name, string optionName, double optionPrice) so that you have just one viewOption

In addition, you have
1
2
3
4
5
6
7
cout << "Enter Quantity:";
cin >> quantity;
if (quantity <= 0)
{
cout << "Invalid Quantity" << endl;
cin >> quantity;
}

in three places. This can be made into a function like
1
2
3
4
5
6
7
8
9
10
11
12
int getQuantity()
{
    int quantity = 0;
    cout << "Enter Quantity:";
	cin >> quantity;
	if (quantity <= 0) // if(quantity < 1)
	{
		cout << "Invalid Quantity" << endl;
		cin >> quantity;
	}
	return quantity;
}

so whenever you need a quantity, you just call there.

That said, this is a modification of your current work.

No arrays, no structs, just functions and many variables

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Use of functions
#include <iostream>
#include <string>

using namespace std;
void displayMenu(string userName);
int getQuantity();
void viewOption(string name, string option, double optionPrice);

int main()
{
    double waterSubTot = 0;
	double sodaSubTot = 0;
	double iceTeaSubTot = 0;

	int waterQty = 0;
	int sodaQty = 0;
	int iceTeaQty = 0;

	double waterPrice = 1.45;
	double sodaPrice = 2.98;
	double iceTeaPrice = 3.29;

	double grandTotal = 0;
	string name;
	char selection = ' ';
	int quantity = 0;
	//Ask user for her/his name
	cout << "Please enter your name ==> ";
	getline(cin, name);
	
	do
	{
                system("cls");
		displayMenu(name);
		// display menu
		//displayMenu(name);
		cout << "Please select: ";
		// read user selection
		cin >> selection;


		switch (selection)
		{
		case '1':
			viewOption(name, "Water", waterPrice);
			quantity = getQuantity();
			waterQty += quantity;
			waterSubTot = waterQty * waterPrice;
			grandTotal += waterSubTot;
			cout << "Subtotal $" << waterSubTot << endl;
			break;
		case '2':
			viewOption(name, "Soda", sodaPrice);
			quantity = getQuantity();
			sodaQty += quantity;
			sodaSubTot = sodaQty * sodaPrice;
			grandTotal += sodaSubTot;
			cout << "Subtotal $" << sodaSubTot << endl;
			break;
		case '3':
			viewOption(name, "Ice tea", iceTeaPrice);
			quantity = getQuantity(),
			iceTeaQty += quantity;
			iceTeaSubTot = iceTeaQty * iceTeaPrice;
			grandTotal += iceTeaSubTot;
			cout << "Subtotal $" << iceTeaSubTot << endl;
			cout << "Thank you!!!" << endl;
			break;
		case 'x':
		case 'X':
			cout << "Grand total: " << grandTotal << endl;
			cout << "Thank you" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again ";
			// no break in the default case
		}
		//total += subtl; //will add all the produce values up. is read as total=total+subt
	} while (selection != 'X' && selection != 'x');//checks if code = 0 at the end of function wont end till it is.
    
    return 0;
}

void displayMenu(string userName)
{
	cout << userName << ", Please select the beverage you would like to purchase from the menu: " << endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1.45" << endl;
	cout << "2 - Soda $2.98" << endl;
	cout << "3 - Iced Tea $3.39" << endl;
	cout << "x - Exit " << endl << endl;
}



void viewOption(string name, string option, double optionPrice)
{
    cout << "Name: " << name << endl;
	cout << "Selection: " << option << " Price: $"<< optionPrice << endl;
}

int getQuantity()
{
    int quantity = 0;
    cout << "Enter Quantity:";
	cin >> quantity;
	if (quantity <= 0)
	{
		cout << "Invalid Quantity" << endl;
		cin >> quantity;
	}
	return quantity;
}


This is how i would solve it. Purely function based Check this: http://cpp.sh/5y33

Hope i have been helpful.
Last edited on
I fixed my code making a lot of chances from you advise and examples. I added system("pause") to stop the function and display the summary, then asks to hit any key to exit the program. The only issue I am having now is if you type in anything other than 1, 2, 3, x or X my invalid message will not display. Please advise my most recent code as follows:

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
// Use of functions
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;


struct Beverage
{
	string name;	// The name
	int quantity{}; // The quantity
	double price{}; //The price

	void info()
	{
		cout << setw(10) << left << "Name" << name << "\n"
			<< setw(10) << left << "Price" << "$" << price << "\n"
			<< setw(10) << left << "Quantity" << quantity << "\n"
			<< setw(10) << left << "Total" << "$"
			<< quantity * price << "\n" << endl;
	}
	void simpleInfo()
	{
		cout << "Selection: " << name << ", price per unit: $" << price << endl;
	}

	Beverage() {}
	~Beverage() {}
	Beverage(string n, double p) {
		name = n;
		price = p;
	}
}; // END OF STRUCT

double totalCost(Beverage beverages[], int numOfBeverages);
void orderSummary(Beverage beverages[], int numOfBeverages);
int getQuantity();
void doShopping();


void displayMenu(string userName) //Menu function
{

	cout << endl << endl
		<< userName
		<< ", Please select the beverage you would like to purchase from the menu: "
		<< endl;

	cout << "Drink Menu" << endl;
	cout << "========" << endl;
	cout << "1 - Water $1" << endl;
	cout << "2 - Soda $2" << endl;
	cout << "3 - Iced Tea $3" << endl;
	cout << "X - Exit " << endl << endl;
}

int main(void)
{
	doShopping();

	return 0;
}


int getQuantity() //Quantity function
{
	int quantity = 0;
	cout << "Enter quantity : ";
	cin >> quantity;
	return quantity;
}


double totalCost(Beverage beverages[], int numOfBeverages)  //Total cost function
{
	double totalCost = 0;

	for (int i = 0; i < numOfBeverages; i++) {
		totalCost += (beverages[i].price*beverages[i].quantity);
	}
	return totalCost;

}


void orderSummary(Beverage beverages[], int numOfBeverages) //Summary function
{
	cout << "\n======= ORDER SUMMARY ====" << endl;
	cout << "Items selected" << endl << endl;
	for (int i = 0; i < numOfBeverages; i++) {
		// only show beverages that has at least one order
		if (beverages[i].quantity > 0) {
			beverages[i].info();
		}
	}
}


void doShopping() //Shopping function
{
	// declare our beverages 
	Beverage water("Water", 1),
		soda("Soda", 2),
		iceTea("Ice Tea", 3);

	// Beverage array to hold the beverages
	Beverage beverages[] = { water, soda, iceTea };

	char selection = ' ';
	string name = "";

	//Ask user for her/his name
	cout << "Please enter your name ==> ";
	getline(cin, name);

	//display user name
	cout << "Hello " + name << endl;

	do
	{
		system("cls");
		// display menu
		displayMenu(name);

		// read user selection
		cout << "Your selection: ";
		cin >> selection;

		switch (selection)
		{
		case '1':
			beverages[0].simpleInfo();
			beverages[0].quantity += getQuantity();
			break;
		case '2':
			beverages[1].simpleInfo();
			beverages[1].quantity += getQuantity();
			break;
		case '3':
			beverages[2].simpleInfo();
			beverages[2].quantity += getQuantity();
			break;
		case 'X':
		case 'x':
			orderSummary(beverages, 3);
			if (totalCost(beverages, 3) > 0) {
				cout << "\nGrand total = $" << totalCost(beverages, 3) << endl;
			}
			cout << "\nThank you for your purchase, " << name << " Come back soon!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x'); // 'X' or 'x' displays the summary
	system("pause"); //Pauses the system until a key is hit, The the program will end.
}
Last edited on
You do not see the error message because of the system("cls");. It clears anything in the console when do{...}while() is re-run

To see it, you have to add these
1
2
3
4
5
6
7
8
9
10
11
// read user selection
		cout << "Your selection: ";
		cin >> selection;
		cin.get();

/// 

default: cout << "Invalid selection. Please try again";
			cin.get();
                       break; // there is no crime in having this here
			// no break in the default case 


Remove the system("pause"); and do like this. https://stackoverflow.com/a/15595559

Notice that when entering quantiy, if you enter a letter, say 'a', the program will not recognize it and will start looping forever.

Use this function
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
bool isAllDigits(string input)
{
	for (unsigned i = 0; i < input.length(); i++) {
		if (!isdigit(input[i])) {
			return false;
		}
	}
	return true;
}

int getValidNumber(string text, int min, int max)
{
	string input{};
	int num{};
	while (true)
	{
		cout << text << " [" << min << " - " << max << "]: ";
		getline(cin, input);

		stringstream ss(input);

		if (!isAllDigits(ss.str())) {
			cout << "\nInvalid input. Try again!" << endl;
		}
		else {
			if (isAllDigits(ss.str()) && ss >> num) {
				if (num >= min && num <= max) {
					break;
				}
				else {
					std::cout << "\nOut of range. Try again!" << endl;
				}
			}
		}
	}
	return num;
}

This will ask for the user to give a valid number until he/she does so.
Try to run this same program in this other version ==> http://cpp.sh/5y33

Again, please read this =>1. Always use code tags http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
blongho,

I see how the other code flows better and does not give errors or infinite loops like mine did. The program still automatically closes when asking for the summary. The link you sent me for stackoverflow. I am assuming you are telling me to try this Properties>Configuration Properties> Linker> System it does not solve the issue for me I tried. What else can I do to fix this issue?
Last edited on
About why the program closes: I have no further suggestions

If you want your getQuantity() to take only correct integer, do these

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
double totalCost(Beverage beverages[], int numOfBeverages);
void orderSummary(Beverage beverages[], int numOfBeverages);
bool isAllDigits(string input);
int getValidNumber(string text, int min, int max);
void doShopping();

///

void doShopping() //Shopping function
{
	// declare our beverages 
	Beverage water("Water", 1),
		soda("Soda", 2),
		iceTea("Ice Tea", 3);

	// Beverage array to hold the beverages
	Beverage beverages[] = { water, soda, iceTea };

	char selection = ' ';
	string name = "";

	//Ask user for her/his name
	cout << "Please enter your name ==> ";
	getline(cin, name);

	//display user name
	cout << "Hello " + name << endl;

	do
	{
		system("cls");
		// display menu
		displayMenu(name);

		// read user selection
		cout << "Your selection: ";
		cin >> selection;
    	       cin.get(); // takes last ENTER character in the stream

		switch (selection)
		{
		case '1':
			beverages[0].simpleInfo();
                        // assuming the customer can shop at least 1 and max 100
			beverages[0].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '2':
			beverages[1].simpleInfo();
			beverages[1].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case '3':
			beverages[2].simpleInfo();
			beverages[2].quantity += getValidNumber("Enter quantity", 1, 100);
			break;
		case 'X':
		case 'x':
			orderSummary(beverages, 3);
			if (totalCost(beverages, 3) > 0) {
				cout << "\nGrand total = $" << totalCost(beverages, 3) << endl;
			}
			cout << "\nThank you for your purchase, " << name << " Come back soon!!!" << endl;
			break;
			// other than 1, 2, 3 and X...
		default: cout << "Invalid selection. Please try again";
			// no break in the default case
		}
		cout << endl << endl;
	} while (selection != 'X' && selection != 'x'); // 'X' or 'x' displays the summary
	system("pause"); //Pauses the system until a key is hit, The the program will end.
}

// And these
bool isAllDigits(string input)
{
	for (unsigned i = 0; i < input.length(); i++) {
		if (!isdigit(input[i])) {
			return false;
		}
	}
	return true;
}

int getValidNumber(string text, int min, int max)
{
	string input{};
	int num{};
	while (true)
	{
		cout << text << " [" << min << " - " << max << "]: ";
		getline(cin, input);

		stringstream ss(input);

		if (!isAllDigits(ss.str())) {
			cout << "\nInvalid input. Try again!" << endl;
		}
		else {
			if (isAllDigits(ss.str()) && ss >> num) {
				if (num >= min && num <= max) {
					break;
				}
				else {
					std::cout << "\nOut of range. Try again!" << endl;
				}
			}
		}
	}
	return num;
}

Last edited on
Topic archived. No new replies allowed.