Program enters infinite loop when validating input

Mar 25, 2013 at 12:50am
Hi, I'm having trouble with this guessing game program in which the user is prompted with whether they want to play a guessing game where the user guesses a number between 1 and 10 that the computer picks from random. The program works fine until it reaches the while loop on line 41, in which if the user enters a character or a letter instead of a number, the program enters an infinite loop. Is there any way to prevent it from doing this? I've tried entering in || usernumber == "" after userNumber > MAX_NUM however this did not work to prevent the infinite loop either. I want it to be able to tell the user that it is invalid input then start back to reasking the question and guess again.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// GuessNumber.cpp - This program allows a user to guess a number between 1 and 10.
// Input:  User guesses numbers until they get it right
// Output: Tells users if they are right or wrong

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

   int number; 	// Number to be guessed
   int userNumber;	// User's guess
   string keepGoing;  // Contains a "Y" or "N" determining if the user wants to continue
    const int MIN_NUM = 1;
    const int MAX_NUM = 10;
   // This is the work done in the detailLoop() function
   srand((unsigned)time(NULL));
   number = (rand() % 10) + 1; // Generate random number

   // Prime the loop
   cout << "Do you want to guess a number? Enter Y or N: " << endl;
   cin >> keepGoing;

   // Validate input
   while(keepGoing != "Y" && keepGoing != "N")
   {
       cout << "Invalid Response. Please type Y or N." << endl;
       cin >> keepGoing;
   }
    // Enter loop if they want to play
   while(keepGoing == "Y")
   {
      // Get user's guess
      cout << "I'm thinking of a number. .\n Try to guess by entering a number between 1 and 10: " << endl;
      cin >> userNumber;
      // Validate input

        while( ((userNumber < MIN_NUM) || (userNumber > MAX_NUM)) )
      {
          cout << "Invalid input. Please type in an number between 1 and 10." << endl;
          cin >> userNumber;
      }


      // Test to see if the user guessed correctly
      if(userNumber == number)
      {
         keepGoing = "N";
         cout << "You are a genius. That's correct!" << endl;
      }
      else
      {
         cout << "That's not correct. Do you want to guess again? Enter Y or N: " << endl;
         cin >> keepGoing;
         // Validate input
        while(keepGoing != "Y" && keepGoing != "N")
        {
            cout << "Invalid Response. Please type Y or N. " << endl;
            cin >> keepGoing;
        }

      }
   } // End of while loop
   return 0;
} // End of main()




Any help would be so greatly appreciated!!
Mar 25, 2013 at 1:22am
Mar 25, 2013 at 4:51am
Thanks! It helped get rid of the infinite loop, however it won't prompt the user again if the user actually does end up entering a number between 1 and 10. You have to enter a number in twice in order for it to prompt you again whether you guessed right or wrong. I feel like I need to insert something in the parentheses for the .clear and .ignore but I'm not sure what parameters to set it by.
1
2
3
4
5
6
7
8
9
10
11
12
13
 while (!(cin >> userNumber) )     // Get the input and validate it
    {
        cin.clear();                    // Clear the error flags
        cin.ignore();          // Remove unwanted characters from buffer
        cout << "Invalid input. Please type in an number between 1 and 10." << endl;  // Re-issue the prompt
        cin >> userNumber;
    }

    while((userNumber < MIN_NUM) || (userNumber > MAX_NUM))
      {
          cout << "Invalid input. Please type in an number between 1 and 10." << endl;
          cin >> userNumber;
      }
Mar 25, 2013 at 5:33am
Get rid of line 6 in the above code. You should probably also merge those two loops.
Mar 25, 2013 at 6:38am
Even better, use a while & switch like this:

http://www.cplusplus.com/forum/beginner/96548/#msg518243


Can also combine with validation like what Oreo has shown above.

Hope all goes well :)
Mar 25, 2013 at 11:55am
Instead of two separate loops, put all the conditions together in a single loop.
1
2
3
4
5
6
        while (!(cin >> userNumber) || (userNumber < MIN_NUM) || (userNumber > MAX_NUM))
        {
            cin.clear();                    // Clear the error flags
            cin.ignore(100, '\n');          // Remove unwanted characters from buffer
            cout << "Invalid input. Please type in an number between 1 and 10." << endl;
        } 
Topic archived. No new replies allowed.