infinite loop...

Hey everyone, complete beginner at c++ here, so go easy on me please :)

Any time I write a program which includes a while loop, I get an error like this:
http://www.youtube.com/watch?v=XOLKSZqLAuc
(I used a dumb little tic-tac-toe program I wrote to demonstrate, but it always happens).

In a nutshell, if I move the cursor (highliter? flashy-position-indicator-thingy?) away from the bottom of the command prompt and then hit enter, an infinite loop occurs, and only ctrl+c can terminate the program. Odd thing is, on the two other computers I've tested this on, I can't even move the cursor. They were both running Windows XP, however, while the laptop in the video is running Win 7. Could that be the problem? As I said, it happens for any while loop, including in code other people have written, so I don't think it's a problem with my code.

Any help is greatly appreciated, I'd like some way to prevent this from happening...
I believe the problem is because when you press "up" on the keyboard, you are sending some characters to the buffer (like ^[ or something). Thus, when cin attempts to read them into an int, it goes into an error state, and since you don't get whether it is ok in your loop, you get an infinite loop.
I guess that would make sense, is there any way to tell cin to ignore the arrow key? I know there's something like a cin.ignore() function but I'm not sure exactly how/if I could use it here.
Well I have no clue if this is going to help but there has been discussion on using cin function throughout the site: http://www.cplusplus.com/forum/beginner/9148/ -for example

From my experience and also those I've heard cin.ignore tends to create a lot more problems than it solves. Also here is a great reference to the cin functions with suggestions for other solutions http://www.cplusplus.com/forum/articles/6046/
Last edited on
Thanks, that article's definitely gonna come in handy. Anyway I started playing around with it and fixed the problem using
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
do
{
	cin>> player2;
	int val = valid(oxopen, player2);
	if (val == 1)
	{
		cout<< "Please choose a number between 1 and 9\n";
	}
	else if (val == 2)
	{
		cout<<"That spot has already been chosen, try again\n";
	}
	cin.clear();
	cin.ignore(1000, '\n');
}
while (valid(oxopen, player2) != 0);


where valid(int[], int) checks if int player2 is an integer between 1 and 9 or has been played already and returns a corresponding error code (or zero if its valid) and that seems to work pretty well. So, problem solved I suppose. Thank you for the replies, however.
Topic archived. No new replies allowed.