Infinate Loop, not for all

This is a discussion on Infinate Loop, not for all within the C++ Programming forums, part of the General Programming Boards category; I'll start by putting up the functions in question: int play() // asks user if they want to play { ...

  1. #1
    Erf
    Erf is offline
    Registered User
    Join Date
    Jul 2004
    Posts
    4

    Infinate Loop, not for all

    I'll start by putting up the functions in question:

    int play() // asks user if they want to play
    {
    cout << "Would you like to play a game of dice with me?\n1.Yes\n2.No";
    bline(1); //writes blank lines
    check();
    return ans;
    }

    int playagn() // asks user if they want to play again
    {
    cout << "Would you like to play again? Please!\n1.Yes\n2.No";
    bline(1);
    check();
    return ans;
    }

    void check() //checks if imput is valid
    {
    cin >> ans;
    while(ans!=1 && ans!=2)
    {
    cout << "Please answer with either 1 or 2";
    while(!cin >> ans)
    {
    cin.clear();
    cin.ignore(std::numeric_limits < int >::max(), '\n');
    }
    bline(1);
    cin >> ans;
    bline(1);
    }
    }

    I took the middle part in check() from the faq, because I was having a problem with infinite looping when the imput was a char and int was expected.
    It works, but only for play(). If I put a char in during playagn(), it goes into an infinite loop, even though the two functions are nearly identical and both use check().

    What's going on here?

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    i would do it using this method eg.
    Code:
    //make a new function
    void getAnswer()
    {
    	int loopVariable=0;
    	while(loopVarible==0)
            {
    	cin>>ans;
    	switch(ans)
    	{
    	case 1:
    		loopVarible=1;
    		break;
    	case 2:
    		loopVarible=1;
    		break;
    	default:
    		validateInput();
    	}
            }
    }
    void validateInput()
    {
    	cin.clear();
    	cin.ignore(numeric_limits<int>::max(),'\n');
    }
    Woop?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. loop in a linked linked lists
    By kris.c in forum C Programming
    Replies: 6
    Last Post: 08-26-2006, 12:38 PM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  4. A somewhat bizzare problem!!! - WHILE LOOP
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 03-31-2006, 06:19 AM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21