Program is in infinite loop for some reason.

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
#include <iostream>

using namespace std;

int main()
{
    int question;
    int play;
        
        cout<<"Hello, and welcome to my MAGIC 8 BALL! \nWould you like to play ( 1 = YES 2 = NO )?"<<endl;
        cin>>question;
        while (question == 1 )
        {
            cout<<"Please give the Magic 8 Ball a question."<<endl;
            cin>>play;
        
            srand((unsigned)time(0)); 
            int random_integer; 
            for(int index=0; index<1; index++)
            { 
                random_integer = (rand()%4)+1; 
                cout <<"\nYou got "<<random_integer<<" which means:"<<endl; 
            
                if (random_integer == 1)
                {
                    cout<<"YES!"<<endl;
                }
                else if (random_integer == 2)
                {
                    cout<<"NO!"<<endl;
                }
                else if (random_integer == 3)
                {
                    cout<<"MAYBE!"<<endl;
                }
                else if (random_integer == 4)
                {
                    cout<<"ASK AGAIN!"<<endl;
                }
            
            }
            cout<<"\nWould you like to ask another question? ( 1 = YES 2 = NO)"<<endl;
            cin>>question;
            
        }
    
    if (question == 2)
    {
        cout<<"Alright bye."<<endl;
    }
    
    return 0;
}
Last edited on
Hint: Try handling input errors.
If you want the user to ask a question (i.e. text/sentence), then change int play; to string play;. Be sure to #include <string>

Also, please use code formatting tags. Read http://www.cplusplus.com/articles/z13hAqkS/ and edit your post.
PLEASE learn to use code tags, it makes reading and commenting on your code MUCH easier.

HINT: you can edit your post and add code tags.

http://www.cplusplus.com/articles/jEywvCM9/

When you enter data for your Magic 8 Ball question are you entering a text question? Trying to stuff text into an int will cause an infinite loop. Enter an integer number and no infinite loop of scrolling text.

Hello, and welcome to my MAGIC 8 BALL!
Would you like to play ( 1 = YES 2 = NO )?
1
Please give the Magic 8 Ball a question.
1

You got 4 which means:
ASK AGAIN!

Would you like to ask another question? ( 1 = YES 2 = NO)
2
Alright bye.


Visual Studio errors out when trying to compile your source as written, you need to include <cstdlib> and <ctime> for the srand/rand and time C library functions.
Topic archived. No new replies allowed.