Cola Machine

Hi everyone,

I found this website today when I was looking for some beginner exercises and it looks like a great community. I decided to try the cola machine exercise and had fun building it, but came across an error.

Can someone tell me why the code outputs incorrectly when someone types in "5." for Tequila instead of "5". Everything else seems to work fine. Thanks in advance!

[output]
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
#include <iostream>

using namespace std;

int main()
{
    int choice;
    string lime;
    cout << "Welcome to the DOS vending machine!" << endl;
    cout << "Please selcet one of the following beverages: " << endl << endl;
    cout << "1. Coke" << endl << "2. Sprite" << endl
         << "3. Rum"  << endl << "4. LSD water" << endl
         << "5. Tequila" << endl << endl;
    cin >> choice;
    if(choice == 1) {
        cout << endl << "Please enjoy your Coke"
        << endl;
    }
    else if (choice == 2) {
        cout << endl << "Enjoy your Sprite, FAG"
        << endl;
    }
    else if (choice == 3) {
        cout << endl << "A pirate's choice, Arggg!"
        << endl;
    }
    else if (choice == 4) {
        cout << endl << "Have a safe trip!"
        << endl;
    }
    else if (choice == 5) {
        cout << endl << "Ole! Would you like a lime? ";
        cin >> lime;

        if (lime == "yes") {
            cout << endl << "Tequila with lime, Amigo" << endl;
        }
        else if (lime == "no") {
            cout << endl << "Tequila straight up, essay!" << endl;
        }
        else {
            cout << endl << "You're not very bright, are you..." << endl;
        }
    }
    else {
        cout << endl << "Error, choice was not valid. Here is your money back" <<
        endl;
    }
    return 0;
}



Hmm. That's odd because it seems to work just fine for me.
Interesting... for me when I type in "5." for Tequila, the output is my first "else if" and the last "else" statement all at once. It doesnt prompt the user like it should if you just type "5"
To my understanding, it should output "Ole! Would you like a lime?" if you input 5, correct? Because that's the output I get.
When you enter "5.", the period is still in the input stream after reading the number and so cin >> lime; reads it. You can use ignore() to discard it, e.g. cin.ignore(1,'\n');
See http://www.cplusplus.com/reference/iostream/istream/ignore/
Last edited on
Oh, I see! So the "5" is being read by (choice == 5) and the "." is being read by cin >> lime;

Thanks a lot! I'm very new and it helps a lot to see how the code is parsed and compiled.
Thanks for all the replies.

Thanks Athar, just finished reading and testing and now I know how to use ignore(). Awesome!
Topic archived. No new replies allowed.