#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    2

    Endless loop in C++


    Hi.
    why does the following code stuck in an endless loop?

    Code:
    int main()
    {
    	string str;
    	int choice=0;
    
    	while (choice!=3)
    	{
    		cout<<"Enter a choice... "<<endl;
    		cin>>choice;
    
    		switch (choice)
    		{
    		case 1:
    			cout<<"Enter a string: "<<endl;
    			cin>>str;
    			break;
    		case 2:
    			cout<<"Does Nothing"<<endl;
    			break;
    		default:
    			break;
    		}
    	}
    }
    My input is:

    Code:
    1
    1
    my string
    and the output is:

    Code:
    Enter a choice... 
    Enter a string: 
    Enter a choice... 
    Enter a string: 
    Enter a choice... 
    Enter a string: 
    Enter a choice... 
    Enter a string: 
    Enter a choice... 
    Enter a string: 
    Enter a choice... 
    Enter a string: 
    ......
    ......
    it only does that for a string with a space in it.
    meaning, for the input:
    Code:
    1
    1
    MyString
    the program works fine.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Posts
    75
    Rep Power
    38
    If you use >> to read a string, it will only read up to the next space. So if you enter "my string", only the "my" will go into the string. The "string" will still be in the buffer, so the next time you try to read an integer, the read operation will fail because "string" is not an integer. Since you never check whether the read fails, this will cause an infinite loop.

    If you want to read a whole line - not just up to the next space -, you'll have to use getline instead of >>.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    2
    Thank you!

IMN logo majestic logo threadwatch logo seochat tools logo