I've just started working my way through Gaddis' Starting out with C++, 5th ed. and have made it through chap. 5. I'm unhappy with my validation code on problem 9 under programming challenges and was hoping to get some help.
For those who don't have the book, the problem is this: User should enter the number of floors in a hotel, then you ask for number of rooms on each floor and how many of those are occupied. Anyhow, it's easy to validate (and loop back until a valid number is entered) as long as the user actually enters a number.
But where I have the problem is if the user enters something other than an integer. I kept trying it with the letter 'g' as user input. Ok, here's a part of my code (same problem occurs if you add Rooms and Occupied as variables):
If I don't include the "break;" statement after the whole cin.fail() thing, then my MS Visual C++ Express compiler just keeps scrolling when the user enters 'g' and doesn't allow another entry. With the "break;" the program at least ends, and my error message is shown.Code:#include <iostream> using namespace std; int main() { int Floors; bool Val = 0; // enter floors do { cout << "How many floors does the hotel have? "; cin >> Floors; if (cin.fail()) { cout << "Invalid entry!\n" << "Close the program and try again.\n"; break; // note this line! } else if (Floors < 1) cout << "The hotel must have at least 1 floor.\n\n"; else if (Floors > 100) cout << "The hotel cannot have more than 100 floors.\n\n"; else Val = 1; } while (Val == 0); return 0; }
What I'd like to do, though, is give the user repeated opportunities to enter valid data for the Rooms variable rather than just forcing a program exit on invalid data.
Any solutions much appreciated--particularly if they only involve things I already know having made it to Gaddis, chap. 5. But I'm happy with any solution that I can follow as C++ newbie.
Thanks!