NewProgrammer NewProgrammer - 1 month ago 11
C++ Question

Do While and While Loops not working in C++ code

Hi I'm writing a C++ code that asks the user for an input as to which internet service provider package they are using, and then using that information the code calculates their monthly bill. However the following code is not working.

{
int choice;
double hours;

cout << "Which Subscription package have you purchased? 1, 2, or 3? " << endl;
cin >> choice;

switch (choice)
{
case 1:
cout << "How many hours were used this month? " << endl; //Package A
cin >> hours;
do{
cout << "Please enter a valid number of hours used. " << endl;
cin >> hours;
} while (hours < 0 || hours > 744);

double monthlyBill; //Calculated as base price + additional hours

if (hours >= 11 || hours <= 744)
monthlyBill = 9.95 + (hours * 2.00);
else
monthlyBill = 9.95;

cout << "Your monthly bill is : $";
cout << monthlyBill << endl;
break;

case 2: //Package B
cout << "How many hours were used this month?" << endl;
cin >> hours;
while (hours < 0 || hours > 744); //Input validation
{
cout << "Please enter a valid number of hours used. " << endl;
cin >> hours;
}

double monthlyBill_b; //Calculated as base price + additional hours

if (hours >= 21 || hours <= 744)
monthlyBill_b = 14.95 + (hours * 1.00);
else
monthlyBill_b = 14.95;

cout << "Your monthly bill is: $ ";
cout << monthlyBill_b << endl;
break;

case 3: //Package C is a flat rate of $19.95 per month
cout << "Your monthly bill is $19.95";
break;
default: cout << "You did not enter 1, 2, or 3. ";
break;
}
}


When run, the code displays the following :


Which Subscription package have you purchased? 1, 2, or 3?


1


How many hours were used this month?


14


Please enter a valid number of hours used.



If any one could provide some insight as to why this isn't working that would be really helpful.

Thanks in advance

Answer
do{     
    cout << "Please enter a valid number of hours used. " << endl;
    cin >> hours;
} while (hours < 0 || hours > 744);

Should be re-written as:

while (hours < 0 || hours > 744) {     
    cout << "Please enter a valid number of hours used. " << endl;
    cin >> hours;
}

In former case you are entering the while unconditionally and then prompting the message and reading new value (unconditionally).

The correct way would be to enter the loop only when the input is out of range.

Comments