I was having dickens of a time figuring out how to keep my program from going into an endless loop when a user enters a character into a double or int data type variable.
For example, I was creating a function with a while loop that would validate the rate entered by the user so it couldn't be a negative rate. It worked well for negative entries; however, this function would go into an endless loop when a character was entered:
double getRate()
{
double dayRate;
cout << "What is the daily charge rate? ";
cin >> dayRate;
// Validate the choice
while (dayRate < 0)
{
cout << "Enter a rate that is not negative.";
cin >> dayRate;
}
return dayRate;
}
In order to fix this, I used "cin.fail()" as a test condition, which would validate whether or not the value entered fits the variable; and then, I flushed the instream and buffer with "cin.clear()" and "cin.ignore()" functions. I'm not 100% sure I understand, but it seems the problem was that "cin >> dayRate" wasn't accepting the character and leaving it in the buffer memory, so that every time the cin operator was going to get the entry, it just kept finding that same character over and over, thus repeating the loop infinitely.
You also need to use "#include <ctype.h>" or "#include <cctype>" (depending on your compiler/system) in the header to call these functions. It works perfect now. I learned this technique at this link - http://www.cplusplus.com/forum/beginner/2957/
double getRate()
{
double dayRate;
cout << "What is the daily charge rate? ";
cin >> dayRate;
// Validate the choice
while ((dayRate < 0) || (cin.fail()))
{
cout << "Enter a valid day rate (no negatives or letters).";
cin.clear();
cin.ignore(1000, '\n');
cin >> dayRate;
}
return dayRate;
}
I had the same problem so I moved the code block back to main and used the functions just to calculate results. I'm going to use your tip in my original program and test it out.
ReplyDelete