cin problem, kinda weird

New to c++ here, I created this code and for some reason the cin gets skipped with a certain case. The code is below

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

int main()
{
    cout << "Menu Chooser Program" << endl;

    cout << "Difficulty Levels\n\n";
    cout << "1 - EASY\n";
    cout << "2 - NORMAL\n";
    cout << "3 - HARD\n";

    int choice;
    char again;

    do
    {
        cout << "Your choice\n";
        cin >>  choice;


        switch (choice)
        {
        case 1:
            cout << "You picked EASY\n";
            break;
        case 2:
            cout << "You picked NORMAL\n";
            break;
        case 3:
            cout << "You picked HARD\n";
            break;
        default:
            cout << "Invalid choice!\n";
        }

        cout <<  "Run again?\n";
        cin >> again;
        cout <<  "Does this code get run?\n";

    }  while (again == 'y');

    srand(time(0));  //seeds random by time

    int randomNumber = rand();   //calls the random number

    int die = (randomNumber % 6) + 1;   //gives you random number between 1 and 6
    cout << "You rolled a " << die << endl;



    return 0;
}


so here is what happens, whenever you enter in say 6, when you are prompted for choice it goes to the default output, like it should. But when you enter in a char value like say u, it goes to the default, like it should, then leaves the switch statement, like it should but then skips over the following cin, it does not wait for it at all, just goes right over it. Probably just something I am not doing right. Any help would be great.
Maybe the issue is just because I am entering a value that is of a different type, and really the program should crash but instead just acts nasty
If you enter something which is not an integer when cin is expecting an int, the fail() flag is set for the cin stream. Any further input will fail until you clear the error flag by doing cin.clear(). It is usually necessary to get rid of the incorrect input by doing cin.ignore() too.

You can simplify this issue if you only need an integer in the range 0 to 9, as these can be handled as a char instead. But if variable choice is changed from type int to type char, the switch-case statements need to reflect this, for example case 1: would need to become case '1':.
Last edited on
I posted a reply but apparently it got deleted... Anyways, thanks for the reply! Very helpful, cleared that up for me. I was pretty sure I was tracing through the code properly. I am use to Java, when something like that happens it just crashes the program ha.

Thanks again!
Topic archived. No new replies allowed.