0

I've got a cin which is looking for a double value, but if a string value of any length is passed, my while loop gets stuck in an infinite output loop.

Here's what I've got:

double milesPerYear = 0;
cin >> milesPerYear;
while (milesPerYear <= 0) {
    cout << "Please input a positive number above 0" << endl;
    cin >> milesPerYear;
}

If the user were to input anything which has a letter in it, it will indefinitely output Please input a positive number above 0.

I want it to prompt the user to input a new value.

Thanks! Nathan

Nathan Lundgren
  • 79
  • 3
  • 14
  • You have to check for bad input. When that arises you need to take step. I.e. eat the bad input – Ed Heal Jan 27 '16 at 20:42
  • When you enter a letter, but it's trying to read a number, the letter sits in the input buffer, and repeated reads won't remove it. You'll want to do something like `std::getline` to clear that out of the buffer before trying to read again. – Jerry Coffin Jan 27 '16 at 20:43
  • I tried adding an or statement to the while: `milesPerYear <= 0 || cin.fail()) {` and this didn't work. – Nathan Lundgren Jan 27 '16 at 20:43
  • @EdHeal How do I check for bad input? – Nathan Lundgren Jan 27 '16 at 20:45

0 Answers0