cin statement being skipped

I'm trying to validate the input of this double price variable. If the input is invalid, i.e. "string" or other non-numeric characters, it goes into an infinite loop filling the console with "Must be new decimal - try again: ". To me the logic reads like it should set tempDbl to a new number, and if it is indeed valid input and is different than book.price, set book.price to the new value and break out of the loop. If not, tempDbl doesn't change and it should loop again. If I enter a valid number like 80.08 it works fine, and if the input is not a number, tempDbl is not set with the new value (which I verified with the debugger - it retains its original value).

When the loop iterates again, it skips the cin >> tempDbl entirely. I set a break point in the loop and stepped through it and it goes right past the cin without accepting input in the console.

Anyone have any tips on how to get this working correctly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct book{
	string title;
	string author;
	double price;
	int onHand;
};
/*snip*/
book Books[8];
/*snip*/
cout << "Enter new price: ";
for(;;){
	tempDbl = Books[book - 1].price;
	cin >> tempDbl;
	if(tempDbl != Books[book - 1].price)
	{
		Books[book - 1].price = tempDbl;
		break;
	}
	else
	{
		cin.ignore();
		cout << "Must be new decimal - try again: ";
	}
}

If the input is not a number, then cin enters an error state, which means any subsequent requests for info will simply be ignored. You have to use .clear() to clear the state and then empty the garbage in the buffer.
What firedraco says, means right after line 13 add:
1
2
       cin.clear();
       cin.ignore();
Cool, thanks guys. Another one down.
Topic archived. No new replies allowed.