Floating points within range and strings in Switch statement

When I enter anything that is a floating point within the range of 0-5 (like 1.7) or any string (like "orange"), it runs forever, and each iteration it displays the ask() and then takes color choice "red" in the switch statement. Why does this happen? Why isn't the default triggered when I enter 1.7 and why
isn't "Bye!\n" triggered when I enter any string? Why is it "red" that equals
the color choice when I enter any string, even strings with spaces ("This has spaces") or enumerator values ("green")?

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
void ask();
void ask()
{
    cout << "Enter a color choice (red=0, green=1, yellow=2, orange=3, blue=4, purple=5)\n";
}

int main ()
{
    enum colors {red, green, yellow, orange, blue, purple};
    ask();
    int color;
    cin >> color;
    while (color<=purple && color >=red) //promoted to int
    {
        switch (color)
        {
            case red : cout << "red\n";
                        break;
            case green : cout << "green\n";
                        break;
            case yellow : cout << "yellow\n";
                        break;
            case orange : cout << "orange\n";
                        break;
            case blue : cout << "blue\n";
                        break;
            case purple : cout << "purple\n";
                        break;
            default : cout << "That's not one of the color choices!\n";
        }
        ask();
        cin >> color;
    }
    cout << "Bye!\n";
    return 0;
}
  
1.7 cannot be read into an integer, so the read operation fails without changing the value of 'color', as well as setting the stream into an error state. Unless you check for failure to read input and clear the error state, all future reads will always fail.
Topic archived. No new replies allowed.