Friday, June 29, 2012

Validating numerical data entered by the user

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;
}


Does anyone understand why we need to add or subtract a "1" to formulas used in C++ programming and Excel formulas when they are not part of the original algebraic equations?
 Ex:   P = _10,000_                                                                                           
              (1 + .042)n

Wednesday, June 20, 2012

Everyone still in class?  I can't log in and it looks like they didn't even bill me for the class.