Input Validation on Array

Advertisements

I am attempting to input validate a user’s value. Criteria: The value inputted cannot be a negative number, in my case the error is encountered when a user enters the wrong value, but instead if reattempting to input the value in the same element it skips over to the next element in the array.

string months[NUM_MONTHS] = {"January", "February", "March", "April", "June", "July", "August", "September", "October", "November", "December"};

int consumption[NUM_MONTHS]; // consumption array

int count; // loop counter

do
{
    for (count = 0; count < NUM_MONTHS; count++)
    {
        cout << "Enter the CCF consumed for " << months[count] << ": ";

        cin >> consumption[count];

        if (consumption[count] < 0)
        {
            cout << "Error: Consumption cannot be a negative integer!" << endl;
        }
    }
} while (consumption[count] < 0);

>Solution :

Looks like you have the right idea, but your loops are the wrong way round. The loop that checks for a negative number should be the inner loop, not the outer loop.

Here’s the correct code

for (int count = 0; count < NUM_MONTHS; count++)
{
    cout << "Enter the CCF consumed for " << months[count] << ": ";

    do
    {
        cin >> consumption[count];

        if (consumption[count] < 0)
        {
            cout << "Error: Consumption cannot be a negative integer!" << endl;
        }
    } while (consumption[count] < 0);
}

Personally I would simplify this, I don’t like the fact that this code checks for a negative number twice. Here’s how I would do it

for (int count = 0; count < NUM_MONTHS; count++)
{
    cout << "Enter the CCF consumed for " << months[count] << ": ";

    // loop until a non-negative number is entered
    for (;;)
    {
        cin >> consumption[count];
        // check number
        if (consumption[count] >= 0)
            break; // non-negative number, quit the loop
        // print error message and try again
        cout << "Error: Consumption cannot be a negative integer!" << endl;
    }
}

But this is a style issue, not everyone will agree with me.

Leave a ReplyCancel reply