cin >> string looping infinitely

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • edyam
    New Member
    • Dec 2007
    • 8

    cin >> string looping infinitely

    Because of a simple cin statement, my program goes into an infinite loop and I'm not sure why. I've used the same code in other programs (only with different variable names and cout statements) and it's worked fine. See code below:

    Code:
    int main () 
    {
    	BinaryHeap pQueue; // create empty heap
    	bool acceptCommand = true;
    	string command; // function to perform
    	
    	while (acceptCommand)
    	{	
    		// get function to perform
    		cout << "Please enter a command: " ;
    		cin >> command ;
    		cout << endl ;
    		
    		// act accordingly
    		if (command=="createHeap")
    		{
    			...
    		}
    	
    		else if (command=="insert")
    		{
    			...
    		}
    	
    		else if (command=="deleteMin")
    		{
    			...
    		}
    		
    		else if (command=="deleteHeap")
    		{
    			...
    		}
    		
    		else if (command=="remove")
    		{
    			...
    		}
    		
    		else if (command=="decreaseKey")
    		{
    			...
    		}
    
    		else if (command=="quit")
    		{
    			acceptCommand = false;			
    		}
    		
    		else // invalid command
    		{
    			cout << "Command not recognized. Please try again." ;
    		}
    		
    	} // end while
    
    	return 0;
    }
    Using a BinaryHeap class and associated functions, the above is supposed to take in a command, act accordingly, and then wait to accept the next instruction. When compiled and run on both XCode and TextMate, the input "createHeap 1 2 3 4 5" will execute the createHeap function correctly once but then attempt to re-execute infinitely. It seems I need to reset the cin variable after the command is given, but cin.clear() and cin.ignore() seem to have no effect. Any suggestions? Thanks in advance.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You dpn't check that con >> command actaully worked.

    If it fails, the input stream goes into a fail state and the operator>> aborts.

    Next time around the operator>> sees the fail state and does nothing.

    And there you are.

    You need to check your >> statements:
    [code=cpp]
    cin >> command;
    if (cin.fail())
    {
    //Here you need to a) cin.clear() to reset the fail state and
    //b) get rid of the data causing the problem
    //etc...
    }
    [/code]

    Comment

    Working...