Help with my small project

Hey guys,

I only started learning C++ about 4 days ago now. I have made a small project however I think I have made a fool of my self and used unnecessary changes etc.

I am trying to get my program to loop so it will keep asking the question.

Here is my source 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
#include <iostream>

using namespace std;

int main(){
int drink[3];
int drinkValues[3] = {1, 2, 3};
cout << "What drink would you like to select?" << endl;
cout << "1 = Cola" << endl << "2 = Fanta" << endl << "3 = Tango" << endl;
cin >> drink[3];

switch(drink[3])
do
{
case 1:
cout << "You have selected a Cola, enjoy!" << endl;
break;
case 2:
cout << "You have selected a Fanta, enjoy!" << endl;
break;
case 3:
cout << "You have selected a Tango, enjoy!" << endl;
break;
default:
cout << "We do not have that drink, sorry!" << endl;
}
while(drink != drinkValues);



return 0;
}


I have a strong feeling the array was not needed? anyway if anyone can help that would be amazing!

thank you.
Hi dataoku,

The size of this array: int drink[3]; is three. Its addresses are 0, 1, and 2, so you can not do cin >> drink[3]. A common mistake, for example: char word[] = "Hello"; has a size of 6, the 6th index being a terminating character.

You can't interrupt a switch the way you have done at line 13. You also need to ask for the drink from within the loop. The array isn't needed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int drink;
do
{
  cout << "What drink would you like to select? (zero to stop)" << endl;
  cout << "1 = Cola" << endl << "2 = Fanta" << endl << "3 = Tango" << endl;
  cin >> drink;
  if (drink > 0)
  {
    switch(drink)
    {
    case 1: /* ... */ break;
    case 2: /* ... */ break;
    case 3: /* ... */ break;
    }
  }
}
while (drink > 0);


The array has some uses, but I wouldn't worry about them for now (for this program at least). Basically, you would do something like this:
1
2
3
4
5
6
7
8
9
10
const int AMOUNT = 3;
const char *drinks[AMOUNT] = {"Cola", "Fanta", "Tango"};

cout << "What do you want to drink?\n";
int coutner = 0;
while (counter < AMOUNT)
{
  cout << counter + 1 << ") " << drinks[counter] << endl;
  counter = counter + 1;
}


With that method you could add more drinks to the list by editing the two lines where it was declared rather than to muck around in code. It would also remove the need for a switch at all.
Last edited on
Thank you for your solution it is greatly appreciated :).
Topic archived. No new replies allowed.